簡體   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