我们可以使用@Input指令将数据从Angular中的Parent传递给Child组件
使用输入绑定: @Input –我们可以在子组件内部使用此伪指令来访问父组件发送的数据。在这里,app.component是Parent组件,cdetail.component是child组件。
父组件
app.component.ts有两个数组。一个用于list_prog –语言列表,prog_details –语言详细信息。
app.component.ts
import { Component } from '@angular/core';
import { AbstractControl, FormBuilder,
FormGroup } from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
list_prog = ['JAVA', 'C++', 'C',
'PYTHON', 'JAVASCRIPT'];
prog_details = [`Java is a widely used
platform independent language. Java was
developed by James Gosling.`, `C++ is
multi-paradigm and procedural oriented
language. Developed by Bjarne Stroustrup.`,
`C is a procedural language and
developed by Dennis Ritchie`, `Python is
a interpreted high level language
developed by Guido van Rossum`,
`Javascript is a language that conforms
the ECMAScript and developed by ECMAScript`];
options: number;
curr_info: string;
prog_title: string;
constructor() {}
onClick(lang) {
switch (lang) {
case 'JAVA':
this.options = 0;
this.curr_info =
this.prog_details[this.options];
this.prog_title =
this.list_prog[this.options];
break;
case 'C++':
this.options = 1;
this.curr_info =
this.prog_details[this.options];
this.prog_title =
this.list_prog[this.options];
break;
case 'C':
this.options = 2;
this.curr_info =
this.prog_details[this.options];
this.prog_title =
this.list_prog[this.options];
break;
case 'PYTHON':
this.options = 3;
this.curr_info =
this.prog_details[this.options];
this.prog_title =
this.list_prog[this.options];
break;
case 'JAVASCRIPT':
this.options = 4;
this.curr_info =
this.prog_details[this.options];
this.prog_title =
this.list_prog[this.options];
break;
default:
break;
}
}
}
HTML
List of Programming Languages
-
{{lang}}
Javascript
import { Component, Input, OnInit } from '@angular/core';
@Component({
selector: 'app-cdetail',
templateUrl: './cdetail.component.html',
styleUrls: ['./cdetail.component.css']
})
export class CdetailComponent implements OnInit {
@Input() details: string;
@Input() title: string;
constructor() { }
ngOnInit(): void {
}
}
HTML
{{title}}
{{details}}
app.component.html在这里,我们在父组件中添加了子组件,并传递了两个数据,一个是prog_title,另一个是curr_info。但是,请确保已在子组件中声明了变量详细信息和标题。
的HTML
List of Programming Languages
-
{{lang}}
子组件
cdetail.component.ts这里我们在子组件内部使用了@Input()指令。现在,在子组件中,可以使用由父组件传递的数据。
Java脚本
import { Component, Input, OnInit } from '@angular/core';
@Component({
selector: 'app-cdetail',
templateUrl: './cdetail.component.html',
styleUrls: ['./cdetail.component.css']
})
export class CdetailComponent implements OnInit {
@Input() details: string;
@Input() title: string;
constructor() { }
ngOnInit(): void {
}
}
cdetail.component.html
的HTML
{{title}}
{{details}}