How do I declare a model class in my Angular 2 component using TypeScript?

后端 未结 8 694
野趣味
野趣味 2020-12-23 11:10

I am new to Angular 2 and TypeScript and I\'m trying to follow best practices.

Instead of using a simple JavaScript model ({ }), I\'m attempting to create a TypeScri

8条回答
  •  独厮守ぢ
    2020-12-23 11:28

    I'd try this:

    Split your Model into a separate file called model.ts:

    export class Model {
        param1: string;
    }
    

    Import it into your component. This will give you the added benefit of being able to use it in other components:

    Import { Model } from './model';
    

    Initialize in the component:

    export class testWidget {
       public model: Model;
       constructor(){
           this.model = new Model();
           this.model.param1 = "your string value here";
       }
    }
    

    Access it appropriately in the html:

    @Component({
          selector: "testWidget",
          template: "
    This is a test and {{model.param1}} is my param.
    " })

    I want to add to the answer a comment made by @PatMigliaccio because it's important to adapt to the latest tools and technologies:

    If you are using angular-cli you can call ng g class model and it will generate it for you. model being replaced with whatever naming you desire.

提交回复
热议问题