打印出个体内部的任何值都不会出现问题,但是使用@Input或@Output获得的任何值都不会正确显示。
我正在尝试使用父属性parentData在child.component.ts中分配childData。
类似地,我正在尝试将子属性“ data”分配给父属性“ data”
child.component.ts
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
@Input() public childData: string;
@Output() public event: EventEmitter<string> = new EventEmitter();
public data = 'Harsha';
constructor() { }
onClick() {
console.log("sending value to parent:"+this.data);
this.event.emit(this.data);
}
ngOnInit() {
}
}
parent.component.ts
@Component({
selector: 'app-parent',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.css']
})
export class ParentComponent implements OnInit {
public parentData = 'Hello Parent';
public data: string;
constructor() { }
onOutputEvent(data: string){
console.log("in parent:"+data);
this.data = data;
}
}
<!-- child.component.html -->
<h3>Printing parent value in child component: {{childData}}</h3>
<h4>Printing child value:{{data}}</h4>
<button (click)="onClick()">Send value to parent</button>
<!-- parent.componnt.html -->
<h3>Printing parent Data: {{parentData}}</h3>
<h4>Printing child Data: {{data}}</h4>
<app-child> [childData]="parentData" (event)="onOutputEvent($event)"</app-child>
<!-- app.component.html -->
<div style="text-align:center">
<h1>
Welcome to {{ title }}!
</h1>
</div>
<app-parent></app-parent>
答案 0 :(得分:1)
您在分配属性之前关闭了标签。
<app-child [childData]="parentData" (event)="onOutputEvent($event)"></app-child>
答案 1 :(得分:0)
您在错误的位置关闭了app-child
指令,请尝试:
<app-child [childData]="parentData" (event)="onOutputEvent($event)"></app-child>