本文介绍了Angular @ViewChild() 错误:需要 2 个参数,但有 1 个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在尝试 ViewChild 时出现错误.错误是未提供‘opts’的参数."

@ViewChild 都给出了错误.

import { Component, OnInit, ElementRef, ViewChild, Output, EventEmitter } from '@angular/core';从src/app/shared/ingredient.model"导入{成分};@成分({选择器:'app-shopping-edit',templateUrl: './shopping-edit.component.html',styleUrls: ['./shopping-edit.component.css']})导出类 ShoppingEditComponent 实现 OnInit {@ViewChild('nameInput') nameInputRef: ElementRef;@ViewChild('amountInput') amountInputRef: ElementRef;@Output() 成分添加 = new EventEmitter();构造函数(){}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 个.

解决方案

在 Angular 8 中,ViewChild 需要 2 个参数

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

When trying ViewChild I am getting the error. Error is "An argument for 'opts' was not provided."

Both @ViewChild is giving the error.

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);
  }

}
解决方案

In Angular 8 , ViewChild takes 2 parameters

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

这篇关于Angular @ViewChild() 错误:需要 2 个参数,但有 1 个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 01:33