Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

viewChild #52

Open
deepthan opened this issue Jun 16, 2020 · 0 comments
Open

viewChild #52

deepthan opened this issue Jun 16, 2020 · 0 comments

Comments

@deepthan
Copy link
Owner

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");
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant