首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如果我从本地引用中获得属性的值,为什么TypeScript要求我初始化它?

如果我从本地引用中获得属性的值,为什么TypeScript要求我初始化它?
EN

Stack Overflow用户
提问于 2022-04-25 14:06:51
回答 2查看 34关注 0票数 0

我才刚开始学角质。

这是我自定义组件的模板

代码语言:javascript
复制
    <div class="row">
  <div class="col-xs-12">
    <form action="">
      <div class="ro">
        <div class="col sm-5 form-group">
          <label for="name">Name</label>
          <input type="text" id="name" class="form-control" #nameInput />
        </div>
        <div class="col-sm-2 form-group">
          <label for="amount">Amount</label>
          <input type="number" id="amount" class="form-control" #amountInput />
        </div>
      </div>
      <div class="row">
        <div class="col-xs-12">
          <button class="btn btn-success" type="submit" (click)="onAddItem()">
            Add
          </button>
          <button class="btn btn-danger" type="button">Delete</button>
          <button class="btn btn-primary" type="button">Clear</button>
        </div>
      </div>
    </form>
  </div>
</div>

这是各自的TypeScript文件

代码语言:javascript
复制
import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';

@Component({
  selector: 'app-shopping-edit',
  templateUrl: './shopping-edit.component.html',
  styleUrls: ['./shopping-edit.component.css'],
})
export class ShoppingEditComponent implements OnInit {
  @ViewChild('nameInput') nameInputRef: ElementRef;
  @ViewChild('amountInput') amountInputRef: ElementRef;

  constructor() {}

  ngOnInit(): void {}
  onAddItem() {}
}

初始化变量nameInputRefamountInputRef时出错。但是我从表格中得到了这些值。我该怎么解决这个问题?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-04-25 14:19:39

类型记录不知道您正在从模板中定义的内容中获取这些值。此外,它们将不会被初始化,直到视图在角度生命周期中被初始化,并且您可能试图在尚未定义的情况下访问它们。

您的问题的答案是使用非空断言操作符!,如下所示

代码语言:javascript
复制
export class ShoppingEditComponent implements OnInit {
 @ViewChild('nameInput') nameInputRef!: ElementRef;
 @ViewChild('amountInput') amountInputRef!: ElementRef;
}

但是,请注意,这是误用运算符,因为,正如前面提到的,可以在尚未定义的情况下访问。

可以使用的第二个方法是展开类型以允许未定义的类型。

代码语言:javascript
复制
@ViewChild('nameInput') nameInputRef: ElementRef | undefined;

但是,在访问任何属性时,必须使用非空断言运算符。

代码语言:javascript
复制
this.nameInputRef!.nativeElement

另外,如果这些元素在组件中是静态的(不受*ngIf或任何条件呈现的约束),则可以将它们标记为静态。这将允许您在组件生命周期的早期通过ngOnInit访问它们。

代码语言:javascript
复制
@ViewChild('nameInput', { static: true }) nameInputRef: ElementRef;
@ViewChild('amountInput', { static: true }) amountInputRef: ElementRef;

如果ViewChild符合这些条件,我总是将它标记为静态的,所以我可以在生命周期的早期访问它们。

票数 1
EN

Stack Overflow用户

发布于 2022-04-25 14:20:05

这可能是因为你处于贴纸模式。解决方案是使用非空断言(感叹号):

代码语言:javascript
复制
@ViewChild('nameInput') nameInputRef!: ElementRef;
@ViewChild('amountInput') amountInputRef!: ElementRef;
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72000867

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档