使用 html 属性title作为结果@Input()会导致奇怪的结果。
运行示例: https: //stackblitz.com/edit/angular-apd2mf
你好.组件.ts
@Component({
selector: 'hello',
template: `<h1>Hello {{title}}{{name}}!</h1>`,
styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent {
@Input() name: string;
@Input() title: string;
}
Run Code Online (Sandbox Code Playgroud)
应用程序组件.ts
@Component({
selector: 'my-app',
template: `
<hello name="{{ name }}" title="Mr. "></hello>
<p>Start editing to see some magic happen :)</p>
`,
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular';
}
Run Code Online (Sandbox Code Playgroud)
这里的问题是,当我title将鼠标悬停在标题上的任何位置时,我会看到输入的值。我知道我可以通过使用它来避免这种情况
<hello name="{{ name }}" [title]="'Mr. '"></hello>
Run Code Online (Sandbox Code Playgroud)
但是,即使我将其声明为输入,Angular 仍附加该属性是否有原因?
为了防止显示工具提示,您可以将自定义title属性定义为 getter/setter,并为titlesetter 中的本机 HTML 属性分配一个空字符串:
private _title: string;
@Input() get title(): string {
return this._title;
}
set title(value: string) {
this._title = value;
this.elementRef.nativeElement.title = "";
}
constructor(private elementRef: ElementRef) { }
Run Code Online (Sandbox Code Playgroud)
请参阅此 stackblitz的演示。
| 归档时间: |
|
| 查看次数: |
5512 次 |
| 最近记录: |