Angular @ViewChild() error: Expected 2 arguments,

2020-01-25 05:32发布

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

}

ts(11,2): error TS2554: Expected 2 arguments, but got 1.

5条回答
▲ chillily
2楼-- · 2020-01-25 05:44

In Angular 8 , ViewChild takes 2 parameters

 @ViewChild(ChildDirective, {static: false}) Component
查看更多
疯言疯语
3楼-- · 2020-01-25 05:46

it is because view child require two argument try like this

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

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

查看更多
SAY GOODBYE
4楼-- · 2020-01-25 05:51

That also resolved my issue.

@ViewChild('map', {static: false}) googleMap;
查看更多
放我归山
5楼-- · 2020-01-25 05:52

In Angular 8, ViewChild has another param

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

You can read more about it here and here

查看更多
欢心
6楼-- · 2020-01-25 05:54

In Angular 8 , ViewChild takes 2 parameters:

Try like this:

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

Explanation:

{ static: false }

If you set static false, the component ALWAYS gets initialized after the view initialization in time for the ngAfterViewInit/ngAfterContentInit callback functions.

{ static: true}

If you set static true, the initialization will take place at the view initialization at ngOnInit

By default you can use { static: false }. If you are creating a dynamic view and want to use the template reference variable, then you should use { static: true}

For more info, you can read this article

Working Demo

In the demo, we will scroll to a div using template reference variable.

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

With { static: true }, we can use this.scrollTo.nativeElement in ngOnInit, but with { static: false }, this.scrollTo will be undefined in ngOnInit , so we can access in only in ngAfterViewInit

查看更多
登录 后发表回答