加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

ng2父子模块通信@ViewChild和@Inject

发布时间:2020-12-17 08:17:43 所属栏目:安全 来源:网络整理
导读:一、@ViewChild 父组件中使用@ViewChild拿到子组件的变量和方法(父组件可调用子组件的方法和变量) parent.component.ts: import { Component,OnInit,ViewChild } from '@angular/core' ;import { ChildComponent } from './child.component' ;@Component({

一、@ViewChild

父组件中使用@ViewChild拿到子组件的变量和方法(父组件可调用子组件的方法和变量)

parent.component.ts:

import { Component,OnInit,ViewChild } from '@angular/core';
import { ChildComponent } from './child.component';

@Component({
  selector: 'my-parent',templateUrl: './parent.component.html',styleUrls: [ './parent.component.css' ],})
export class ParentComponent implements OnInit {
  //通过@ViewChild注册子组件
  @ViewChild(ChildComponent) public child:ChildComponent;
  public countNum: number;
  public firstName:string = "Jeck";
  public fullName:string = "";

  constructor() {}

  ngOnInit(): void {

  }
  displayFull(){
    this.fullName = this.firstName + this.child.lastName;
   console.log(this.fullName)  //"Jeck wang"
  }
}

child.component.ts:

import { Component,OnInit} from '@angular/core';

@Component({
  selector: 'my-child',templateUrl: './child.component.html',styleUrls: [ './child.component.css' ],})
export class ChildComponent implements OnInit {
  public lastName:string = "wang";

  constructor() {}

  ngOnInit(): void {

  }

}

二、@Inject

子组件中使用@Inject调用父组件中的变量和方法

parent.component.ts:

import { Component,OnInit } from '@angular/core';

@Component({
  selector: 'my-parent',})
export class ParentComponent implements OnInit {

  constructor() {}

  ngOnInit(): void {

  }
  sayHello(){
    console.log("Hello!")
  }
}

child.component.ts:

import { Component,Inject,forwardRef} from '@angular/core';
import { ParentComponent } from './parent.component';

@Component({
  selector: 'my-child',})
export class ChildComponent implements OnInit {

  constructor(
    @Inject(forwardRef(()=>ParentComponent)) public parent:ParentComponent
  ) {}

  ngOnInit(): void {
    this.parent.sayHello();   //"Hello!"
  }
}

注意:如果父子模块通过以上方式相互引用,请在父模块中使用 @ViewChild(forwardRef(()=>ChildComponent)) public child:ChildComponent 方式避免父子组件循环引用报错

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读