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.
模板引用变量通常用来引用模板中的某个 DOM 元素,也可以引用 Angular 组件、指令、Web Component(自定义元素标签)。
store.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-store',
templateUrl: './store.component.html',
styleUrls: ['./store.component.css']
})
export class StoreComponent implements OnInit {
name = 'SUV';
constructor() { }
ngOnInit() {
}
}
store.component.html
<!-- 引用DOM元素 -->
<span #title>4S店</span>
<button (click)="print(title.innerHTML);">单击</button>
<input type="tel" #tel value="021-12345678"/>
<button (click)="print(tel.value);">单击</button>
<!-- 引用Angular组件 -->
<app-car #car></app-car>
<button (click)="print(car.name);">单击</button>
car.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-car',
templateUrl: './car.component.html',
styleUrls: ['./car.component.css']
})
export class CarComponent implements OnInit {
name = 'SUV';
constructor() { }
ngOnInit() {
}
}