Skip to content

viewChild #52

Open
Open
@deepthan

Description

@deepthan

viewChild

作用

在ts中获取组件的引用,可以主动触发引入组件的方法

使用方法

  • 假设有个子组件

子组件ts

import { Component } from "@angular/core";
@Component({
  selector: "son-comp",
  template: `<p>子组件</p>`,
})
export class SonComponent {
    play(){
        console.log("调用了");
    }
};

方法1: 父组件ts中引入子组件

父组件ts

import { Component, viewChild } from "@angular/core";
import { SonComponent } from "./son.component.ts"
@Component({
  selector: "parent-comp",
  template: `<p (click)="click()">点击调用子组件方法</p>`,
})
export class ParentComponent {
    @ViewChild(SonComponent) 
    sonRef: SonComponent;
    
    click(){
        this.sonRef.play();
    }
};

方法2: 父组件html中引入子组件

父组件ts

import { Component, viewChild } from "@angular/core";
import { SonComponent } from "./son.component.ts"
@Component({
  selector: "parent-comp",
  template: `
  <son-comp #son></son-comp>
  <p (click)="click()">点击调用子组件方法</p>
  `,
})
export class ParentComponent {
    @ViewChild("son") 
    sonRef: any;
    
    click(){
        this.sonRef.play();
    }
};

获取子组件的dom

  • 假设有个子组件
@Component({
	selector: 'demo', 
	template: `
    	<ul>
            <li></li>
        </ul>
	`
})
export class xxx {}
  • 父组件想获取到它里面的元素
<demo #demo></demo>
import { ViewChild, ElementRef } from '@angular/core';
export class xxx {
    @ViewChild('demo') demo: ElementRef;
    
    constructor(){
          const parentElement = this.demo.element;
          const firstChild = parentElement.children[0];
          const firstImage = parentElement.querySelector("li");
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions