相关疑难解决方法(0)

有没有办法将类型断言/注释添加到模板输入变量?

背景

我有一个看起来像这样的模板(我使用的是一个使用它作为重复项的基础的组件,它是p-pickList,但问题并不是特定于该组件,仅作为示例)

对于背景,假设我有一个类型Foo,我的组件有一个foos: Foo[],我将它提供给属性<p-pickList>下的组件,[source]并为它做内部*ngFor,我所要做的就是提供一个模板

 <ng-template let-foo pTemplate="item">
   ...
   {{ foo.anythingGoesHereWithNoWarningAndNoAutocomplete }}
Run Code Online (Sandbox Code Playgroud)

但是,类型信息foo似乎丢失了.

我是类型安全的忠实粉丝,我喜欢Intellij(或任何其他编辑器)可以在模板内部向我显示警告我做了类似指定无效属性的事情 foo

如果我有一个常规*ngFor,它会推断出类型foo

<div *ngFor="let foo of foos">
  {{ foo.autoCompleteWorksInMostIDEsAsWellAsWarningIfInvalidProp }}
Run Code Online (Sandbox Code Playgroud)

问题:

  1. 是否有任何语法可以让我提示类型let-foo?(希望大多数IDE都能识别).

  2. 如果我不想依赖IDE,有没有办法让ng编译器类型检查foo(由let-foo声明)?

tl; dr是否有一种语法可以让我输入注释模板输入变量?例如这样的东西组成语法?

let-foo="$implicit as Foo"还是let-foo-type="Foo"

解决方法

一个愚蠢的想法是在我的组件中有一个身份功能,例如

identity(foo: Foo): Foo {
  return foo;
}
Run Code Online (Sandbox Code Playgroud)

但是做

{{ identity(foo).fooProp }}

不是一个很大的进步

{{ (foo as Foo).fooProp }}

angular angular6

22
推荐指数
1
解决办法
1174
查看次数

ng-template-类型变量

父组件如何识别let-content其来源 类型ngTemplateOutletContext?现在{{content.type}}可以正常工作,但是IDE会说:

未解析的变量类型

如何输入为Video

parent.component.ts:

export interface Video {
  id: number;
  duration: number;
  type: string;
}

public videos: Video = [{id: 1, duration: 30, type: 'documentary'}];
Run Code Online (Sandbox Code Playgroud)

parent.component.html:

<ul>
  <li *ngFor="let video of videos">
    <tile [bodyTemplate]="tileTemplate" [content]="video"></app-card>
  </li>
</ul>

<ng-template #tileTemplate let-content>
  <h5 class="tile__type">{{content.type}}</h5>
</ng-template>
Run Code Online (Sandbox Code Playgroud)

tile.component.ts:

@Component({
  selector: 'tile',
  templateUrl: './tile.component.html',
  styleUrls: ['./tile.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class CardComponent {
  @Input() tileTemplate: TemplateRef<any>;
  @Input() content: Video;
}
Run Code Online (Sandbox Code Playgroud)

tile.component.html:

<div
...
  <ng-container
    [ngTemplateOutlet]="tileTemplate"
    [ngTemplateOutletContext]="{ …
Run Code Online (Sandbox Code Playgroud)

typescript angular

8
推荐指数
3
解决办法
1026
查看次数

标签 统计

angular ×2

angular6 ×1

typescript ×1