Angular父组件传值给子组件

(传的值可以是属性,方法等)
1.在父组件news.component.ts里的:(传值方式与vue有点类似)

export class NewComponent implements OnInit {
	//在这里定义和获取要传递的值,例如:
	public name = '我是发哥';
	public age = 'age';
	run (){
		alert("父组件传给子组件的run方法")
	}
}

2.在父组件news.component.html里的子组件标签里绑定属性:

//有一个是自定义名字的
    <div class="news">
    <app-header [title]="title" [name]="name" [run]="run"></app-header>
    </div>

3.在子组件news.component.ts里接收父组件传过来的值:

3-1.需导入Input:
	 import { Component, OnInit ,Input} from '@angular/core';
	 
3-2.通过 @Input()接收传过来的值,可以说明值是什么类型
    @Input() title;
    @Input() name:string;
     @Input() run; //run方法
    
3-3.然后可在news.component.html里显示父组件传过来的值:
 	<p>tilte--{{title}}</p>
 	<p>name--{{name}}</p>
 	<button (click)="run()">执行父组件传过来的run方法</button>

猜你喜欢

转载自blog.csdn.net/qq_43579525/article/details/83935122