angular ViewChild

以你之姓@ 2023-06-13 03:22 12阅读 0赞

ViewChild 用于操作dom树元素,或是对操作子组件

一、操作dom元素

先用#xxx来标记dom元素

news.component.html

  1. <div #myBox>
  2. 我是一个dom节点
  3. </div>

引入ViewChild,用@ViewChild绑定一个变量。nativeElement是真实的dom节点

news.component.ts

  1. import { Component, OnInit, ViewChild } from '@angular/core';
  2. @Component({
  3. selector: 'app-news',
  4. templateUrl: './news.component.html',
  5. styleUrls: ['./news.component.scss']
  6. })
  7. export class NewsComponent implements OnInit {
  8. @ViewChild('myBox',{static:false}) myBox:any;
  9. constructor() { }
  10. ngOnInit() {
  11. }
  12. ngAfterViewInit(): void {
  13. console.log(this.myBox);
  14. this.myBox.nativeElement.style.width='200px';
  15. this.myBox.nativeElement.style.height='100px';
  16. this.myBox.nativeElement.style.background='red';
  17. console.log(this.myBox.nativeElement);
  18. console.log(this.myBox.nativeElement.innerHTML);
  19. }
  20. }

结果:

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzM0NDE2MzMx_size_16_color_FFFFFF_t_70

二、操作子组件

和操作dom元素一样,创建实例

  1. // 获取子组件
  2. @ViewChild('header',{static:false}) myHeader:any;

子组件:

header.component.html

  1. <h1>我是一个头部组件</h1>

header.component.ts

  1. import { Component, OnInit } from '@angular/core';
  2. @Component({
  3. selector: 'app-header',
  4. templateUrl: './header.component.html',
  5. styleUrls: ['./header.component.css']
  6. })
  7. export class HeaderComponent implements OnInit {
  8. constructor() { }
  9. ngOnInit() {
  10. }
  11. run() {
  12. alert('调用header组件的run()');
  13. }
  14. }

在父组件中调用:

  1. getChildRun(): void {
  2. // 调用子组件的方法
  3. this.myHeader.run();
  4. }

发表评论

表情:
评论列表 (有 0 条评论,12人围观)

还没有评论,来说两句吧...

相关阅读