Angular 6-将编译后创建的HTML绑定到click事件

时间:2018-12-04 11:06:00

标签: html angular typescript innerhtml

我在用户单击按钮时在运行时添加HTML元素。

我这样做是通过将div的内部html设置为构建的字符串,然后使用DOMSanitizer。

在外观上看起来不错,但是新HTML中的click事件未绑定,因此没有任何作用,因为HTML是在编译后生成的。

这是当用户单击以添加新组件(它填充了正确的数据)时调用的代码,有人可以建议我如何将其连接到删除图像中的click事件吗?

页面上的

html:

<div class="col-sm-9" >
      <div [innerHtml]="contentHtml"></div>
</div>

代码:

async AddText(contentText: string) {
    this.htmlToAdd = this.htmlToAdd + ( '<br> <div class="card text-left">' +
    '<div class="card-header text-secondary">Attraction Text' +
      '<img  align="right" class="image-hover pull-right table-header-padding" src="assets/images/LockLineIcon.png" />' +
      '<img #delete class="image-hover float-right text-danger icon-pad draft-icon-indent" src="assets/images/DeleteIcon.png" (click)="this.delete(0)"/>' +
    '</div>' +
    '<div class="card-body" >' +

    '<textarea  id="text" name="text" type="text" class="form-control" required maxlength="2048" >' + contentText + '</textarea>' +
    '</div>' +
    '<div class="card-footer">' +
      '<img align="right" class="pull-right table-header-padding" src="assets/images/DragUpDownIcon.png" />' +
    '</div>' +
  '</div>');
  this.contentHtml = this.sanitizer.bypassSecurityTrustHtml(this.htmlToAdd);
  }

1 个答案:

答案 0 :(得分:0)

您的DOM可能已被清除,但它不是Angular DOM的一部分。如果您希望Angular看到DOM,则必须让Angular制作DOM-这意味着动态组件。这样的事情会起作用:

@Component({
  selector: 'my-component',
  template: `<h2>Stuff bellow will get dynamically created and injected<h2>
          <div #vc></div>`
})
export class MyComponent {
  @ViewChild('vc', {read: ViewContainerRef}) vc: ViewContainerRef;

  private cmpRef: ComponentRef<any>;

  constructor(private compiler: Compiler,
              private injector: Injector,
              private moduleRef: NgModuleRef<any>,
              private backendService: backendService,
              ) {}

  ngAfterViewInit() {
    // Here, get your HTML from wherever.
    this.someService.getThatAsyncHTMLOfYours.subscribe(rawHTML => this.createComponentFromRaw(rawHTML));
  }

  // Here we create the component.
  private createComponentFromRaw(template: string) {
    // Let's say your template looks like `<h2><some-component [data]="data"></some-component>`
    // As you see, it has an (existing) angular component `some-component` and it injects it [data]

    // Now we create a new component. It has that template, and we can even give it data.
    const tmpCmp = Component({ template, styles })(class {
      // the class is anonymous. But it's a quite regular angular class. You could add @Inputs,
      // @Outputs, inject stuff etc.
      data: { some: 'data'};
      ngOnInit() {
        /**
         * HERE'S YOUR STUFF
         * do stuff here in the dynamic component, like binding to locally available variables and services.
         */
      }
    });