zoukankan      html  css  js  c++  java
  • Angular组件——父组件调用子组件方法

    viewChild装饰器。

    父组件的模版和控制器里调用子组件的API。

    1、创建一个子组件child1里面只有一个greeting方法供父组件调用。

    import { Component, OnInit } from '@angular/core';
    
    @Component({
      selector: 'app-child1',
      templateUrl: './child1.component.html',
      styleUrls: ['./child1.component.css']
    })
    export class Child1Component implements OnInit {
    
      constructor() { }
    
      ngOnInit() {
      }
    
      greeting(name: string) {
        console.log("hello" + name);
      }
    
    }
    View Code

    2、父组件中分别在模版中用模版本地变量调用在控制器中用ts代码调用。

    父组件写2个<app-child>并分别指定模版本地变量

    <app-child1 #child1> </app-child1>
    <app-child1 #child2> </app-child1>

    3,在父组件控制器中声明一个由viewChild装饰器装饰的变量获得子组件的引用。

    通过模版变量的名字child1找到相应的子组件并赋值给child1变量,拿到引用就可以调用子组件方法。

    @ViewChild('child1')
    child1:Child1Component; //父组件中获得子组件的引用
    
    ngOnInit(){
      this.child1.greeting("Tom");
    }

    4,在父组件模版中调用子组件方法。

    在父组件模版中加一个button,点击时去调用子组件child2的greeting方法。

    <app-child1 #child1> </app-child1>
    <app-child1 #child2> </app-child1>
    <button (click)="child2.greeting('Jerry')">调用child2的greeting方法</button>

    本文作者starof,因知识本身在变化,作者也在不断学习成长,文章内容也不定时更新,为避免误导读者,方便追根溯源,请诸位转载注明出处:http://www.cnblogs.com/starof/p/8689908.html  有问题欢迎与我讨论,共同进步。

  • 相关阅读:
    团队作业—第二阶段08
    团队作业—第二阶段07
    java--Map使用实现模拟斗地主洗牌发牌
    课程作业08 MVC框架具体使用
    课程作业 MVC框架
    课堂作业06_23种设计模式
    课堂作业05 《6种质量属性战术》
    课堂作业04
    课堂作业03
    架构漫谈阅读笔记
  • 原文地址:https://www.cnblogs.com/starof/p/8689908.html
Copyright © 2011-2022 走看看