Angular 的最新版本需要对变量进行初始化。我该如何解决?

Angular's recent version requires initialization for variables. How can I fix it?

下面的代码适用于旧的 Angular 版本。

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <input type="text" [(ngModel)]="value">
    <p>{{ value | reverse }}</p>
  `
})
export class AppComponent {
  value: string;
}

但是,由于以下错误,相同的代码在 Angular 的最新版本中不起作用。

Property 'value' has no initializer and is not definitely assigned in the constructor.

Can't bind to 'ngModel' since it isn't a known property of 'input'.

Type 'Event' is not assignable to type 'string'.

当我查找此问题的解决方案时,我找到了两个解决方案:1. 使用空值进行初始化({}、'' 等)2. 使用安全导航运算符 (?)。但是,这两个都不行。

第一个解决方案仅适用于某些情况,但不适用于此。

另外,遇到连初始化都不能用空值的情况怎么办。例如,如果上面的 'value' 变量是一个接口,我就不能尝试初始化它。

谢谢,

在这种情况下我会考虑的一件事是在使用 ng-container 的模板中有一个默认值。

<ng-container *ngIf="value?.length > 0"></ng-container>

这样反向管道就不会期待未定义的值。 Angular 在这里是先发制人的,所以我倾向于在我的模板中做同样的事情 UI。