web-dev-qa-db-ja.com

Angular @ViewChild()エラー:2つの引数が必要ですが、1つ取得されました

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になりました。

191
stack overflow

Angular 8では、ViewChildは2つのパラメーターを取ります

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

角度8

Angular 8、ViewChildには別のパラメーターがあります

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

あなたはそれについてもっと読むことができます herehere

角度9

Angular 9のデフォルト値はstatic: falseであるため、{static: true}を使用する場合を除き、paramを指定する必要はありません。

72
Reza

In 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 }を使用すると、ngOnInitthis.scrollTo.nativeElementを使用できますが、{ static: false }を使用すると、this.scrollToundefinedngOnInitになります_なので、ngAfterViewInitでのみアクセスできます

19
Adrita Sharma

ビューの子が2つの引数を必要とするためです

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

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

5
paras shah

IDEA経由ですべてを置換するための正規表現(Webstormでテスト済み)

検索:\@ViewChild\('(.*)'\)

置換:\@ViewChild\('$1', \{static: true\}\)

0
Torsten Simon

In Angular 8、ViewChildは常に2つのパラメータを取り、2番目のパラメータは常にstatic:trueまたはstatic:falseを持ちます

あなたはこのように試すことができます:

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

また、static: falseは、Angular 9.のデフォルトのフォールバック動作になります。

静的false/trueとは何ですか:経験則として、次のことを実行できます。

  • { static: true }は、ngOnInitでViewChildにアクセスするときに設定する必要があります。

    { static: false }はngAfterViewInitでのみアクセスできます。これは、テンプレートの要素に構造ディレクティブ(つまり、* ngIf)がある場合にも使用したいものです。

0
Pinki Dhakad