【问题标题】:Dynamic inner html event not working in Angular 8动态内部 html 事件在 Angular 8 中不起作用
【发布时间】:2020-01-21 11:42:52
【问题描述】:

这些是我的代码

child.component.ts

import { Component, Input, OnInit, EventEmitter, Output } from '@angular/core';
import { DomSanitizer } from "@angular/platform-browser";

@Component({
  selector: 'child-component',
  templateUrl: './child.component.html',
})
export class ChildComponent implements OnInit {
  @Input() dataFromParent: String;
  @Output() sendDataToParent = new EventEmitter<string>();
  htmldata:any;

  constructor(private sanitizer: DomSanitizer){

  }

  ngOnInit() {
    this.htmldata = '<input type="text" #data><button (click)="_sendDataToParent(data.value)">Send event to parent</button>';

    console.log('This is data from parents', this.dataFromParent);
    console.log('this.htmldata', this.htmldata);
  }

  _sendDataToParent(data:string) {
    console.log('you clicked');
    this.sendDataToParent.emit(data);
  }

  makeSanitize(str: any)
  {
    return this.sanitizer.bypassSecurityTrustHtml(str);
  }
}

child.component.html

<h2>Child Component</h2>
<p>{{dataFromParent}}</p>
<span [innerHTML]="makeSanitize(htmldata)"></span>

app.component.html

<h2>Parent Component</h2>
<p>
    {{dataFromChild}}
</p>

<hr>
<hr>
<hr>

<child-component 
  [dataFromParent]="'This is data sent from parent'"
  (sendDataToParent)="eventFromChild($event)">
</child-component>

app.component.ts

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

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular 6';
  dataFromChild;
  eventFromChild(data) {
    console.log(data);
    this.dataFromChild = data;
  }
}

我打算动态生成htmldata

htmldata 在其子组件中有 innerhtml 值。 Innerhtml 也有 Click 事件不起作用。

我想填写输入并单击Send event to parent 按钮。但是没有触发事件。

亲爱的开发者请帮帮我

【问题讨论】:

  • 朋友请任何人指导我

标签: angular typescript events click innerhtml


【解决方案1】:

您在字符串值中编码“角度”,然后将其放入 DOM。 Angular 代码需要编译成真正的 html/js 代码

因此,您需要先写“onclick”而不是“(click)” 但是随后您将遇到其他错误,例如“_sendDataToParent 未定义”,因为您需要该函数一个“脚本”标签

看这里测试https://stackblitz.com/edit/angular-4s9fzs

最后,在字符串中生成角度代码,然后将其放入 DOM 可能是您不想做的事情

【讨论】:

  • 感谢您的回复。当我输入输入文本并单击发送到父按钮Error occurred (1:1) _sendDataToParent is not defined 时出现这样的错误
  • 是的,正如我的评论中所述,您需要进行其他更改才能使其正常工作,因为它不再是有角度的,而是普通的 html 答案:“但是您将遇到其他错误,例如“_sendDataToParent 未定义” 您需要在“脚本”标签中使用该函数
  • 对不起,这不是我想要的。我也想通过这个函数传递一些参数。有没有办法让它使用“点击”而不是“点击”来工作
猜你喜欢
  • 1970-01-01
  • 2017-11-30
  • 1970-01-01
  • 1970-01-01
  • 2019-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-04
相关资源
最近更新 更多