HTML文件:
元素1
元素2
组件的TypeScript文件:
import { Component, ViewChild, ElementRef } from '@angular/core';
@Component({
selector: 'app-example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.css']
})
export class ExampleComponent {
@ViewChild('element1', {static: true}) element1: ElementRef;
@ViewChild('element2', {static: true}) element2: ElementRef;
onClick() {
this.element1.nativeElement.style.color = 'red';
this.element2.nativeElement.style.background = 'blue';
}
}
请注意,需要确保Angular的版本是10或更高。
这样,当点击按钮时,元素1的文本颜色将变为红色,元素2的背景颜色将变为蓝色。