我想通過@Input傳遞一個自定義對象。但是,我得到null作爲輸出。爲什麼在@Input中傳遞自定義對象不起作用?
這是我的孩子組件類:
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;
}
}
在父類的HTML即app.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};
只是工作正常?
請分享你的父母組件代碼也 –
@ARUN我剛纔做 – BlackBeard