我有一个约定对象,必须作为子组件的输入传递,当我在子模板中调用它时,会显示约定id,但当我试图在console.log中使用约定时,会出现未定义的情况。我尝试将我的console.log放在子构造函数以及ngOnInit、ngAfterViewInit和ngOnChanges中。对于ngOnChanges,当我只将约定的id作为子组件的输入传递时,它工作得很好,但是我需要传递约定而不是它的id。
index.component.ts
@Component({
templateUrl: './index.template.html',
selector: 'be-convention-update',
changeDetection: ChangeDetectionStrategy.OnPush
})
export class ConventionUpdateComponent {
private convention$: Convention;
private conventionId: number;
constructor(private route: ActivatedRoute,
private conventionService: ConventionService) {
this.route.params.subscribe(
(params: any) => {
this.conventionId = params['id'];
this.conventionService.getOne(this.conventionId).subscribe(response => this.convention$ = response);
}
);
}
}
index.template.html
<be-form-convention [convention]="convention$"></be-form-convention>
form.component.ts
@Component({
selector: 'be-form-convention',
templateUrl: './form.template.html',
changeDetection: ChangeDetectionStrategy.OnPush
})
export class ConventionFormComponent implements OnChanges, OnInit {
@Input() convention: Convention;
constructor() {
}
public ngAfterViewInit() {
console.log(this.convention); //undefined
}
public ngOnInit(): void {
console.log(this.convention); //undefined
}
public ngOnChanges(changes: SimpleChanges): void {
const object: SimpleChange = changes.convention;
console.log('prev value: ', object.previousValue); //undefined
console.log('got name: ', object.currentValue); //undefined
}
}
发布于 2018-04-08 03:42:48
根据我的理解,当您接收到输入或输入值更改时,您希望做一些操作。
可以在set函数中使用输入指令,如下所示:
_convention: Convention;
@Input()
set convention(convention: Convention) {
this._convention = convention;
//the code you want to handle after input is received
}
发布于 2018-04-08 06:34:56
由于这是一个异步操作,我建议您等到约定获得值时再使用*ngIf
加载子组件,而约定对象不是空的。
<ng-container *ngIf="convention$">
<be-form-convention [convention]="convention$"></be-form-convention>
</ng-container>
发布于 2018-04-08 04:18:38
对于组件-组件通信,我总是使用服务。
我所做的是:创建一个服务并创建两个函数(getData和setData)。
每当我想将一些数据从一个组件发送到另一个组件时,我就调用setData方法,当我想在其他组件中接收数据时,我使用getData方法。
下面是一个示例:
从“@角/核心”导入{ Injectable };
@Injectable()
export class DataExchange {
data; //Global Variable of 'any' type.
setData(data){
this.data = data;
}
getData():any{
return this.data;
}
}
https://stackoverflow.com/questions/49717314
复制相似问题