【发布时间】:2018-06-03 21:21:46
【问题描述】:
我正在尝试理解 Angular 4 中的继承。
下面是我的 AppComponent 文件:
import { Component,OnInit } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
title = 'app';
myArray= ["1","2","3"]; //THIS WORKS
//myArray:any; //Declared but not initialized
setTitle(value:any){
this.title=value;
console.log(this.myArray[2]);
}
ngOnInit(){
//this.myArray=["1","2","3"]; //THIS DOESNT WORK
}
}
这是另一个扩展 AppComponent 的组件
import { Component, blurbs } from '@angular/core';
import { AppComponent } from '../app.component';
@Component({
selector: 'app-child',
templateUrl: `<p>
title {{title}}
<button (click)="setTitle('child')">change title</button>
</p>`,
styleUrls: ['./child.component.css']
})
export class ChildComponent extends AppComponent implements OnInit {
constructor() {
super();
}
ngOnInit() {
}
}
在上面的代码中,我从 ChildComponent 调用 setTitle() 方法。
我有一个 myArray[2] 的控制台日志。
如果我在声明它时初始化值,则该值可以正常工作。
但如果我只是在 ngOnInit 块中声明和初始化数组,console.log 不起作用并告诉我 myArray[2] 未定义。
我的应用程序中有类似的场景,谁能指导我什么是正确的方法以及为什么当我在 ngOnInit 块中初始化数组时它不起作用
【问题讨论】:
标签: angular typescript inheritance ecmascript-6 components