父组件访问子组件,以news包含footer为例
1、@ViewChild(’’)
①在父组件引入子组件的html中给子组件加id
<app-footer #footer></app-footer>
②在父组件中引入ViewChild
import { Component, OnInit, ViewChild } from '@angular/core';
引入子组件
@ViewChild('footer') footer:any
2、@output EventEmitter
①在子组件中引入
import { Component, OnInit, Output, EventEmitter } from '@angular/core';
②在子组件中声明
@Output() private outer=new EventEmitter()
即可通过this.outer.emit("我是footer中的数据")语法广播
③在子组件绑定(调用父组件的run() 方法即可访问父组件属性,同时通过$event实 现父组件访问子组件数据)
<app-footer (outer)="run($event)"></app-footer>
子组件访问父组件,以home包含header为例
@input()
①在父组件绑定属性到子组件上
<app-header [title]="title" [msg]="msg" [run]="run" [home]="this"></app-header>
②子组件导入input
import { Component, OnInit, Input } from '@angular/core';
③即可通过@Input() title:any访问