角@ViewChild()错误:预期有2个参数,但得到1个

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)

  • 如果元素需要在 ngOnInit 期间可用,则 static 需要为“true”,但如果它可以等到 init 之后,则可以为“false”,这意味着它在 ngAfterViewInit/ngAfterContentInit 之前才可用。 (14认同)
  • 谢谢。有效。你能告诉我这是什么意思吗? (8认同)
  • 您可以将其标记为接受吗?来自Angular docs:静态-是否在更改检测运行之前解析查询结果(即仅返回静态结果)。如果未提供此选项,则编译器将退回到其默认行为,即使用查询结果来确定查询解析的时间。如果任何查询结果在嵌套视图中(例如* ngIf),则将在运行更改检测后解决查询。否则,将在运行更改检测之前解决该问题。 (4认同)
  • 如果您希望他接受您的答案作为最佳答案,则应在答案中添加该答案 (4认同)
  • 注意:要保持Angular 7的行为,您需要指定`{static:true}`。ng update将帮助您在需要时自动执行此操作。或者,如果您已经将依赖项升级到Angular 8,则此命令将帮助您迁移代码:ng update @ angular / core-from 7-to 8 --migrate-only (4认同)

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.nativeElementin ngOnInit,但是 with { static: false }, this.scrollTo将在undefinedin 中ngOnInit,所以我们只能在 in 中访问ngAfterViewInit


par*_*hah 5

这是因为查看子项需要两个参数这样尝试

@ViewChild('nameInput',{static:false,})nameInputRef:ElementRef;

@ViewChild('amountInput',{static:false,})amountInputRef:ElementRef;