Type checking in Angular 2 templates

后端 未结 7 515
夕颜
夕颜 2021-02-02 06:07

We are building an application in Angular 2 and TypeScript. We try to statically check types where it is possible. Is there any way to check types in templates? Consider the fol

相关标签:
7条回答
  • 2021-02-02 06:37

    Your components Input() should have the type. Let's say you have a list component

    import {Component, Input, OnInit } from '@angular/core';
    
    import { Items } from '../../../services/Items';
    
    @Component({
      selector: 'my-list',
      templateUrl: './my-list.component.html',
      styleUrls: ['./my-list.component.scss'],
    })
    export class CategoryListComponent implements OnInit {
      @Input() items: Items;
    
      constructor() { }
    
      ngOnInit() { }
    }
    

    "Items" should be defined as a interface and imported

    export interface List {
      name: string,
      children: Items[]
    }
    
    export interface Item {
      name: string;
      slug: string;
      imageUrl: string;
      children: Item[];
    }
    

    now you can use it like this

    <my-list [items]="items"></my-list>
    
    0 讨论(0)
提交回复
热议问题