其他分享
首页 > 其他分享> > angular 学习笔记之父子组件传值@Input @Output @ViewChild

angular 学习笔记之父子组件传值@Input @Output @ViewChild

作者:互联网

style.css全局的css.(单纯写在这 和本次无关)

一、 父组件给子组件传值 -@Input

1. 父组件调用子组件的时候传入数据(news.html)

<app-header [msg]="msg"></app-header>

2. 子组件引入Input模块(header.ts文件)

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

3. 子组件中 @Input接收父组件传过来的数据

export class HeaderComponent implements OnInit {
  @Input() msg:string
  constructor() { }
  ngOnInit() {
  }
}

4. 子组件中使用父组件的数据(header.html)

<h2>这是头部组件--{{msg}}</h2>

二、 父子组件传值的方式让子组件执行父组件的方法

1. 父组件定义方法

run(){
  alert('这是父组件的run 方法');
}

2.调用子组件传入当前方法

<app-header [msg]="msg" [run]="run"></app-header>

3. 子组件接收父组件传过来的方法

import { Component, OnInit ,Input } from '@angular/core'; 
    @Input() run:any;
export class HeaderComponent implements OnInit { 
    @Input() msg:string 
    @Input() run:any; 
    constructor() { } 
}

4. 子组件使用父组件的方法。

export class HeaderComponent implements OnInit { 
    @Input() msg:string;
    @Input() run:any; 
    constructor() { } 
    ngOnInit() { 
        this.run(); /*子组件调用父组件的run方法*/ 
    }
}    

 

标签:run,msg,ViewChild,export,Input,组件,Output,OnInit
来源: https://www.cnblogs.com/zhaoqiusheng/p/11116009.html