How to insert HTML inside an Angular component 4?

2

Hello! How to insert an HTML code inside a component in Angular? For example:

I have the component button:

whose code is:

<button type="submit"></button>

I would like to insert the html in this way:

<app-button>Teste</app-button>

so that the code of the component looks like this, dynamic:

<button type="submit">Teste</button>

I know it's possible, but I still have not found how. Thank you in advance.

    
asked by anonymous 21.01.2018 / 02:01

2 answers

4

You are looking for the tag ng-content it allows you to access what was passed in the body of the component.

Example:

import {Component} from '@angular/core';

@Component({
  selector: 'custom-component',
  template: '<button>
              <ng-content></ng-content>
              </button>',
})
export class CustomComponent{

}

Using the above component, you can create it and pass text on your body.

<custom-component>BOTÃO CUSTOMIZADO </custom-component>

Angular will render the following html:

<custom-component>
   <button> BOTÃO CUSTOMIZADO </button>
</custom-component>

I've created an example in stackblitz for you

    
26.01.2018 / 00:48
5

You must create a variable to receive the values within the component. Here's an example:

@Component({
    selector: 'app-button',
    template: '
        <button type="submit">{{label}}</button>
    ',
})

export class AppButtonComponent {
    @Input() label: string;
}

This will cause you to declare the label variable at the time you create the component, like this:

<app-button [label]="'Teste'"></app-button>

Note that I declared the name "Test" inside single quotation marks because I am declaring it manually. If it were another variable within your other component, you could pass the variable directly, without the need for quotation marks, like this:

<app-button [label]="minhaVariavel"></app-button>
  

Note : You can not declare anything inside the app-button statement because when rendering, Angular will replace what you declared manually by what was declared in the template or co_de property %.

    
21.01.2018 / 12:52