Atualização 2
Caso não queira fazer o uso de biblioteca, você pode usar a classe Compiler ( Obs.: Não confundir com $compile
do AngularJS )
Arquivo app.component.ts
import { Compiler, Component, Injector, NgModule, NgModuleRef, ViewChild, ViewContainerRef } from "@angular/core";
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
@ViewChild('testando', { read: ViewContainerRef }) _container: ViewContainerRef;
constructor(private _compiler: Compiler, private _injector: Injector, private _m: NgModuleRef<any>) { }
test() {
alert('Teste :D');
}
ngAfterViewInit() {
const html_string = '<input type="button" (click)="test()" value={{btnValue}}>';
const tmpCmp = Component({ template: html_string })(class { });
const tmpModule = NgModule({ declarations: [tmpCmp] })(class { });
this._compiler.compileModuleAndAllComponentsAsync(tmpModule)
.then((factories) => {
const f = factories.componentFactories[0];
const cmpRef = f.create(this._injector, [], null, this._m);
cmpRef.instance.btnValue = 'CLIQUE!';
cmpRef.instance.test = this.test;
this._container.insert(cmpRef.hostView);
})
}
}
Arquivo app.component.html
<div #testando></div>
Veja funcionando em stackblitz
O exemplo acima foi adaptado do artigo: Here is what you need to know about dynamic components in Angular. ( Aqui está o que você precisa saber sobre componentes dinâmicos em Angular - Tradução livre. )
Atualização 1
Fazendo uma pesquisa no Google, encontrei a biblioteca p3x-angular-compile.
Para utilizar, basta seguir os passos:
Importar a biblioteca no arquivo app.module.ts
import { CompileModule} from 'p3x-angular-compile';
Configurar o modulo:
@NgModule({
imports: [ ... CompileModule],
...
})
Código do template:
<div *ngIf="true"
[p3x-compile]="html_string"
[p3x-compile-ctx]="this" >
</div>
Usar seu componente normalmente assim como esta na pergunta, com a exceção que os eventos devem ser precedidos por context.
:
html_string = `<input type="button" (click)="context.test('wmsouza')" value="CLIQUE AQUI!">`;
test(nome) {
alert(`Olá, ${nome}`);
}
Podes ver funcionando em stackblitz
Isso não é possível, pois a subclasse DomSanitizer
simplesmente ignora, a solução seria utilizar o método addEventListener
para registrar um evento no elemento.
import { Component, ChangeDetectorRef, ElementRef } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
html_string;
constructor(private sanitizer: DomSanitizer, private elRef: ElementRef, private cdRef: ChangeDetectorRef) { }
test = (nome) => {
alert(`Olá, ${nome}`);
}
ngOnInit() {
this.html_string = this.sanitizer.bypassSecurityTrustHtml('<input type="button" value="CLIQUE AQUI!">');
this.cdRef.detectChanges();
this.elRef.nativeElement.querySelector('input').addEventListener('click', _ => { this.test('wmsouza') }, false);
}
}
Veja funcionando em stackblitz