繁体   English   中英

BEGINNER Angular4组件故障排除

[英]BEGINNER Angular4 Component Trouble Shoot

****更新代码*****
嘿,每个刚接触angular 4的人,我都试图制作一个简单的组件,该组件显示从该对象获取其数据的月份和日期

这是我的data.model.ts文件

export class Dater {

    date = new Date();
    month: number = this.date.getMonth(); 
    day: number = this.date.getDate();

    constructor() {
    }

}

我收到以下错误
Cannot find name 'date' Did you mean instance member 'this.date'?

然后是我的date.component.ts文件

import { Component, OnInit } from '@angular/core';
import { Dater } from './dater.model'; // here i reference my date class
@Component({
  selector: 'app-date',
  templateUrl: './date.component.html',
  styleUrls: ['./date.component.css']
})
export class DateComponent implements OnInit {

  date: Dater; // assign property to type Date class
  constructor() { 
  }
  ngOnInit() {
  }

}

和我的视图文件date.component.html

<p>
  date works!
  {{date.month}}
</p>

我还要补充一点,我对OOP的理解不是很好,是的:)感谢所有帮助!

更新我的代码后,我现在得到以下错误
Cannot read property 'month' of undefined

有两个错误,您不应将keyword作为类名,并且当您将this与打字稿一起使用时,

以下应该工作,

export class myClass {
    date = new Date();
    month: number = this.date.getMonth();
    day: number = this.date.getDate();
    constructor() {
    }

}

在组件范围内,我们使用this来引用属性或函数,即类上下文。

export class Dater {

   date: Date = new Date();
   month: number = this.date.getMonth(); 
   day: number = this.date.getDate();

   constructor() {

   }

}`

在模板中,表达式上下文通常是组件实例(对象上下文),在这种情况下是DateComponent对象上下文。

我们错过了声明实例,因此它将是不确定的。

import { Component, OnInit } from '@angular/core';
import { Dater } from './dater.model'; // here i reference my date class
@Component({
  selector: 'app-date',
  templateUrl: './date.component.html',
  styleUrls: ['./date.component.css']
})
export class DateComponent implements OnInit {

  date: Dater = new Dater();
  constructor() { 
  }
  ngOnInit() {
  }

}

您可以参考此Angular 2文档以了解有关Angular 2上下文的更多信息https://angular.io/docs/ts/latest/guide/template-syntax.html

这纯粹是Typescript类的实例化问题,其中未在DateComponent.ts中实例化模型中的Dater类。您可以在https://www.typescriptlang.org/docs/handbook/classes.html中了解有关Typescript类的更多信息。

date = new Dater();  

这将解决问题

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM