Angular全局变量有时未定义

时间:2018-01-12 17:37:34

标签: angular typescript components

我有一个组件,它接受一个用于构造本地字符串的@Input变量。这发生在ngOnChanges中。然后我的HTML包含一个查找此局部变量的* ngIf。我的问题/问题是在验证变量已经设置后,我的* ngIf没有显示。我使用局部变量将控制台日志输入到ngAfterViewChecked中,并显示我的变量在未识别和设置之间切换。最后,在我验证了varible已经设置之后,我的元素没有显示出来。我在这里缺少什么?

.TS

@Input() type: string;

title: string;

constructor() { }

ngOnChanges() {
    console.log('into ngOnChanges');       

    if (this.type) {
        console.log('this.type is', this.type);
        this.title = this.type + ' is the type';
        console.log('title is', this.title);
    }
}

ngAfterViewChecked() {
    console.log('afterViewChecked title is', this.title);
}

.HTML

<span *ngIf="title" class="uppercase">{{title}}</span>

console.logs

into ngOnChanges
this.type is something
title is something is the type
afterViewChecked title is undefined
afterViewChecked title is something is the type
afterViewChecked title is undefined

此外,我将一个带有click事件的按钮放到记录变量的方法中。日志吐出标题未定义但是以下afterViewChecked日志重复上面的内容....'undefined'...''某种类型'...'undefined'。

.TS

whatIsTitle() {
    console.log('what is title...', this.title);
}

.HMTL(按钮)

<button (click)="whatIsTitle()" class="btn btn-sm btn-default">Title?</button>

的console.log

what is title... undefined
afterViewChecked title is undefined
afterViewChecked title is something is the type
afterViewChecked title is undefined

更新 这是一个链接到stackblitz我嘲笑了解释一点点进一步。 https://stackblitz.com/edit/angular-yyttwp

这是有效的,并没有显示我遇到的问题的迹象。所以现在我正在用我的项目查看其他环境变量,因为上面的代码看起来显然正常工作(至少根据stackblitz)

更新2 我没有得到任何环境变量,但我只是想更新我发现的东西。看来这个问题并不是几个变量所独有的。如果我在ngAfterViewChecked中的标题日志旁边放置一个'this'的日志,我可以看到整个组件中的所有内容都恢复为未定义。

.TS

console.log('this is...', this);

控制台登录浏览器

afterViewChecked title is undefined
afterViewChecked this is... >Component {} 
afterViewChecked title is something is the type
afterViewChecked this is... >Component {type: "something", title: "something is the type" } 
afterViewChecked title is undefined
afterViewChecked this is... >Component {} 

1 个答案:

答案 0 :(得分:-1)

这是因为您的标题和类型未定义。我已手动尝试初始化这些变量,但您可以根据您的要求初始化它们。

import {Input, OnChanges, SimpleChanges} from '@angular/core'

export class App implements OnChanges{
@Input() type ='hi';

title: string = 'hi';
constructor() { }

ngOnChanges(changes: SimpleChanges) {
console.log('into ngOnChanges');       

if (this.type) {
    console.log('this.type is', this.type);
    this.title = this.type + ' is the type';
    console.log('title is', this.title);
}
}
whatIsTitle() {
console.log('what is title...', this.title);
}

ngAfterViewChecked() {
console.log('afterViewChecked title is', this.title);
}
}

Plunker demo

另外,请查看UpgradeComponent课程以获取更深入的参考资料

相关问题