Dev*_*Ara 1 typescript angular angular8
我想动态创建一个按钮。我使用innerHtml 来做到这一点。我可以创建按钮。但它的点击事件不起作用。请告诉我如何解决这个问题?
这是我的 html 代码
<div [innerHTML]="answerPanelContent"></div>
Run Code Online (Sandbox Code Playgroud)
这是我的打字稿代码
answerPanelContent: any;
constructor(private sanitizer: DomSanitizer){
}
ngOnInit() {
this.answerPanelContent = this.sanitizer.bypassSecurityTrustHtml(`<button type="button" class="btn btn-primary float-left"
(click)="removeAnswer()" title="Remove Answer"
aria-label="Close">
Remove</button>`);
}
removeAnswer(){
alert('clicked');
}
Run Code Online (Sandbox Code Playgroud)
这是 stackblitz 网址:https ://stackblitz.com/edit/angular-nka4w9
我强烈建议不要[innerHTML]为此使用。它不是为了这个目的,也不是“角度方式”。
这是解决您的问题和“角度方式”的最可取方法。
组件.ts
export class AppComponent {
public buttonsTexts:Array<string> = ['First button'];
public addButton(index:number):void {
this.buttonsTexts = [...this.buttonsTexts, `button ${index}`];
}
}
Run Code Online (Sandbox Code Playgroud)
模板.html
<button
*ngFor="let buttonText of buttonsTexts; let i = index;"
(click)="addButton(i)">{{buttonText}}</button>
Run Code Online (Sandbox Code Playgroud)
仅当*ngFor由于我们不知道的某些要求而无法解决您的问题时才使用此选项。
组件.ts:
export class AppComponent implements AfterViewInit {
@ViewChild('inserttarget', {static: false})
public insertTarget:ElementRef; // use this if you want to insert inside a specific element in your template
constructor(
private renderer:Renderer2,
private el:ElementRef // use this if you want to insert into your template's root
) {
}
public ngAfterViewInit():void {
this.addNewButton();
}
public addNewButton():void {
const button = this.renderer.createElement('button');
const buttonText = this.renderer.createText('Click me');
this.renderer.appendChild(button, buttonText);
this.renderer.appendChild(this.insertTarget.nativeElement, button); // use this.el.nativeElement to insert into template root
this.renderer.listen(button, 'click', () => this.addNewButton());
}
}
Run Code Online (Sandbox Code Playgroud)
模板.ts
<p #inserttarget>
Some text
</p>
Run Code Online (Sandbox Code Playgroud)
这是一个有效的StackBlitz。
| 归档时间: |
|
| 查看次数: |
6273 次 |
| 最近记录: |