[英]What is the meaning of the syntax: <element #foo />
I am reading a tutorial and I have found a sample code with a line looking like this: 我正在阅读教程,并且找到了带有以下代码的示例代码:
<input #foo />
I think that it's an input with id="foo". 我认为这是id =“ foo”的输入。 But isn't the correct syntax this one:
但是这不是正确的语法:
<input id="foo" />
It's called a template reference variable in Angular. 在Angular中称为模板参考变量。 it can refer to a DOM element,Directive or web component etc. According to the official documentation -
它可以引用DOM元素,指令或Web组件等。根据官方文档-
A template reference variable is often a reference to a DOM element within a template. It can also be a reference to an Angular component or directive or a web component.
Source : https://angular.io/guide/template-syntax#ref-vars 来源: https : //angular.io/guide/template-syntax#ref-vars
Example : We can use @ViewChild()
with Template Variable using ElementRef
to access Native Element. 示例:我们可以将
@ViewChild()
与模板变量一起使用ElementRef
来访问本机元素。 @ViewChild()
can instantiate ElementRef
corresponding to a given template reference variable. @ViewChild()
可以实例化与给定模板引用变量相对应的ElementRef
。 The template variable name will be passed in @ViewChild()
as an argument. 模板变量名称将在
@ViewChild()
作为参数传递。
HTML : HTML:
<div>
Name: <input type="text" #name> <br/>
City: <input type="text" #city>
</div>
Component code : 组件代码:
import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core';
@Component({
selector: 'app-theme',
templateUrl: './apptheme.component.html'
})
export class AppThemeComponent implements AfterViewInit {
@ViewChild('name')
private elName : ElementRef;
@ViewChild('city')
private elCity : ElementRef;
ngAfterViewInit() {
this.elName.nativeElement.style.backgroundColor = 'cyan';
this.elName.nativeElement.style.color = 'red';
this.elCity.nativeElement.style.backgroundColor = 'cyan';
this.elCity.nativeElement.style.color = 'red';
}
}
using #name and #city
above we can access the native elements style properties. 使用上面的
#name and #city
,我们可以访问本机元素样式属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.