当尝试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);
  }

}

ts(11,2):错误TS2554:期望2个参数,但得到1。


角8

在Angular 8中,ViewChild有另一个参数

@ViewChild('nameInput', {static: false}) component : Component

你可以在这里和这里读到更多信息

Angular 9和Angular 10

在Angular 9中,默认值是static: false,所以不需要提供参数,除非你想使用{static: true}

这是因为viewchild需要两个参数,像这样尝试

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

在Angular 8中,ViewChild接受2个参数

 @ViewChild(ChildDirective, {static: false}) Component

这也解决了我的问题。

@ViewChild('map', {static: false}) googleMap;

在Angular 8中,ViewChild接受2个参数:

试着这样做:

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

解释:

{static: false}

如果你设置static为false,子组件总是在视图初始化后被ngAfterViewInit/ngAfterContentInit回调函数及时初始化。

{static: true}

如果你设置static为true,子组件初始化将发生在ngOnInit的视图初始化处

默认情况下,您可以使用{static: false}。如果你正在创建一个动态视图,并且想要使用模板引用变量,那么你应该使用{static: true}

要了解更多信息,你可以阅读这篇文章

演示工作

在演示中,我们将使用模板引用变量滚动到div。

 @ViewChild("scrollDiv", { static: true }) scrollTo: ElementRef;

对于{static: true},我们可以在ngOnInit中使用this. scrollto . nativeelement,但是对于{static: false}, this. scrollto . nativeelement。scrollTo在ngOnInit中是未定义的,所以我们只能在ngAfterViewInit中访问in

Regex替换所有通过IDEA (Webstorm测试)

觉得:\ @ViewChild。 \('(.*)'\)

替换:\@ViewChild\('$1', \{static: true\}\)

在Angular 8中,ViewChild总是接受2个参数,第二个参数也总是 Static: true或Static: false

你可以这样尝试:

@ViewChild('nameInput', {static: false}) component

同样,static: false将是Angular 9中的默认回退行为。

什么是静态错误/正确: 所以根据经验,你可以选择以下方法:

对象时需要设置{static: true} ViewChild在ngOnInit中。 {static: false}只能在ngAfterViewInit中访问。这是 当你有一个结构指令的时候你想要做什么 (即*ngIf)在模板中的元素上。

你应该像这样使用ViewChild的第二个参数:

@ViewChild("eleDiv", { static: false }) someElement: ElementRef;

使用这个

@ViewChild(ChildDirective, {static: false}

在Angular 8中,ViewChild有另一个参数

@ViewChild('nameInput', {static: false})组件

我解决我的问题如下

@ViewChild(MatSort, {static: false}) sort: MatSort;

在angular 8.0中试试这个:

@ViewChild('result',{static: false}) resultElement: ElementRef;