我才刚开始学角质。
这是我自定义组件的模板
<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文件
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() {}
}初始化变量nameInputRef和amountInputRef时出错。但是我从表格中得到了这些值。我该怎么解决这个问题?
发布于 2022-04-25 14:19:39
类型记录不知道您正在从模板中定义的内容中获取这些值。此外,它们将不会被初始化,直到视图在角度生命周期中被初始化,并且您可能试图在尚未定义的情况下访问它们。
您的问题的答案是使用非空断言操作符!,如下所示
export class ShoppingEditComponent implements OnInit {
@ViewChild('nameInput') nameInputRef!: ElementRef;
@ViewChild('amountInput') amountInputRef!: ElementRef;
}但是,请注意,这是误用运算符,因为,正如前面提到的,可以在尚未定义的情况下访问。
可以使用的第二个方法是展开类型以允许未定义的类型。
@ViewChild('nameInput') nameInputRef: ElementRef | undefined;但是,在访问任何属性时,必须使用非空断言运算符。
this.nameInputRef!.nativeElement另外,如果这些元素在组件中是静态的(不受*ngIf或任何条件呈现的约束),则可以将它们标记为静态。这将允许您在组件生命周期的早期通过ngOnInit访问它们。
@ViewChild('nameInput', { static: true }) nameInputRef: ElementRef;
@ViewChild('amountInput', { static: true }) amountInputRef: ElementRef;如果ViewChild符合这些条件,我总是将它标记为静态的,所以我可以在生命周期的早期访问它们。
发布于 2022-04-25 14:20:05
这可能是因为你处于贴纸模式。解决方案是使用非空断言(感叹号):
@ViewChild('nameInput') nameInputRef!: ElementRef;
@ViewChild('amountInput') amountInputRef!: ElementRef;https://stackoverflow.com/questions/72000867
复制相似问题