我正在尝试通过@Input 传递自定义对象。但是,我得到null作为输出。
这是我的子组件类:
import { Component, OnInit, Input } from '@angular/core';
import { Element } from '../app.element';
@Component({
selector: 'app-server-element',
templateUrl: './server-element.component.html',
styleUrls: ['./server-element.component.css']
})
export class ServerElementComponent implements OnInit {
// @Input('srvElement') element: {type: string, name: string, content: string}; <--- This works
@Input('srvElement') ele:Element; <--- This doesn't work
constructor() { }
ngOnInit() { }
}
这是我的element
课:
export class Element{
type: string;
name: string;
content: string;
constructor(type: string="", name: string="", content: string=""){
this.type = type;
this.name = name;
this.content = content;
}
}
在父类的 htmlapp.component.html
中,我有这个(与子类通信):
<div class="container">
<app-cockpit (notify)="onNotifyClicked($event)"></app-cockpit>
<hr>
<div class="row">
<div class="col-xs-12">
<app-server-element *ngFor="let serverElement of serverElements"
[srvElement]="serverElement"></app-server-element>
</div>
</div>
</div>
父类即app.component.ts
:
import { Component } from '@angular/core';
import { Element } from './app.element';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
serverElements = [{type: 'server', name: 'Testserver', content: 'Just a test'}];
element: {type: string, name: string, content: string};
onNotifyClicked(e: Element){
if(e.type==='server'){
this.serverElements.push({
type: 'server',
name: e.name,
content: e.content
});
} else {
this.serverElements.push({
type: 'blueprint',
name: e.name,
content: e.content
});
}
}
}
任何人都可以向我解释为什么@Input('srvElement') ele:Element;
不工作也不 @Input('srvElement') let ele=new Element();
行(传递我自己的自定义对象)但@Input('srvElement') element: {type: string, name: string, content: string};
工作正常?