这是一个非常基本的示例,显示了角度为7的高图图片。 与其将值直接从选项传递到data []对象,我不希望通过使用hello-component中的@input装饰器通过app.component中声明的值来实现。 但是运行ng服务时,出现“无法读取未定义的属性'直接'”错误。请帮忙吗?非常感谢你!
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'passComponent';
aces: number;
constructor() {
this.aces = 5;
}
}
hello-component.component.ts
import { Component, OnInit, Input} from '@angular/core';
import * as Highcharts from 'highcharts';
@Component({
selector: 'app-hello-component',
templateUrl: './hello-component.component.html',
styleUrls: ['./hello-component.component.css']
})
export class HelloComponentComponent implements OnInit {
@Input() direct: number;
public options: any = {
chart: {
type: 'column',
height: 700
},
title: {
text: 'Sample Scatter Plot'
},
credits: {
enabled: false
},
tooltip: {
formatter: function() {
return 'x: ' + Highcharts.dateFormat('%e %b %y %H:%M:%S', this.x) + 'y: ' + this.y.toFixed(2);
}
},
xAxis: {
categories: ['RG', 'WM']
},
series: [
{
name: 'Normal',
data: (function() {
var datos = [];
for (let i = 0; i <=1; i += 1) {
datos.push({
x: i,
y: this.direct + i
});
}
return datos;
}())
}
]
}
ngOnInit(){
Highcharts.chart('container', this.options);
}
}
hello-component.component.html
<p>{{direct}} direct</p>
<div id="container"></div>
app.component.html
<div>
<!-- <app-hello-component direct="5"></app-hello-component> -->
<app-hello-component [direct]="aces"></app-hello-component>
</div>
答案 0 :(得分:0)
这是因为有Angular生命周期方法,您通常要分配值OnInit
(在初始化组件模板时)。仅当值已初始化时才渲染元素也是有意义的。因此,要纠正此问题,您需要将代码更改为:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'passComponent';
aces: number;
ngOnInit() {
this.aces = 5;
}
}
<div *ngIf="aces">
<!-- <app-hello-component direct="5"></app-hello-component> -->
<app-hello-component [direct]="aces"></app-hello-component>
</div>