sta*_*low 118 typescript angular
尝试Viewchild时出现错误。错误是“未提供'opts'参数。”
@ViewChild都给出了错误。
import { Component, OnInit, ElementRef, ViewChild, Output, EventEmitter } from '@angular/core';
import { Ingredient } from 'src/app/shared/ingredient.model';
@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;
@Output() ingredientAdded = new EventEmitter<Ingredient>();
constructor() {}
ngOnInit() {
}
onAddItem() {
const ingName = this.nameInputRef.nativeElement.value;
const ingAmount = this.amountInputRef.nativeElement.value;
const newIngredient = new Ingredient(ingName, ingAmount);
this.ingredientAdded.emit(newIngredient);
}
}
Run Code Online (Sandbox Code Playgroud)
ts(11,2):错误TS2554:预期有2个参数,但得到1。
Jen*_*sen 237
在Angular 8中,ViewChild采用2个参数
@ViewChild(ChildDirective, {static: false}) Component
Run Code Online (Sandbox Code Playgroud)
Rez*_*eza 55
在Angular 8中,ViewChild具有另一个参数
@ViewChild('nameInput', {static: false}) component
Run Code Online (Sandbox Code Playgroud)
Adr*_*rma 35
在 Angular 8 中,ViewChild
需要 2 个参数:
像这样尝试:
@ViewChild('nameInput', { static: false }) nameInputRef: ElementRef;
Run Code Online (Sandbox Code Playgroud)
解释:
{静态:假}
如果您设置static false,则子组件总是在视图初始化后及时为ngAfterViewInit/ngAfterContentInit
回调函数进行初始化。
{静态:真实}
如果设置static true,则子组件初始化将在视图初始化时进行ngOnInit
默认情况下,您可以使用{ static: false }
. 如果您正在创建动态视图并希望使用模板引用变量,那么您应该使用 { static: true}
有关更多信息,您可以阅读这篇文章
在演示中,我们将使用模板引用变量滚动到一个 div。
@ViewChild("scrollDiv", { static: true }) scrollTo: ElementRef;
Run Code Online (Sandbox Code Playgroud)
with { static: true }
, 我们可以使用this.scrollTo.nativeElement
in ngOnInit
,但是 with { static: false }
, this.scrollTo
将在undefined
in 中ngOnInit
,所以我们只能在 in 中访问ngAfterViewInit
这是因为查看子项需要两个参数这样尝试
@ViewChild('nameInput',{static:false,})nameInputRef:ElementRef;
@ViewChild('amountInput',{static:false,})amountInputRef:ElementRef;
归档时间: |
|
查看次数: |
46736 次 |
最近记录: |