[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을 받았습니다.



답변

Angular 8에서 ViewChild는 2 개의 매개 변수를 사용합니다.

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


답변

앵귤러 8

Angular 8에서 ViewChild에는 다른 매개 변수가 있습니다.

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

여기여기에 대해 더 자세히 읽을 수 있습니다

앵귤러 9

에서 Angular 9기본값입니다 static: false, 그래서 당신은 사용하지 않으려면 PARAM를 제공 할 필요가 없습니다{static: true}


답변

Angular 8에서는 ViewChild두 가지 매개 변수를 사용합니다.

이렇게 해보십시오 :

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

설명:

{정적 : 거짓}

static false 를 설정 하면 ngAfterViewInit/ngAfterContentInit콜백 함수에 대한 뷰 초기화 시간이 지나면 컴포넌트 ALWAYS가 항상 초기화됩니다 .

{정적 : true}

static true로 설정 하면 초기화는 다음 위치의 뷰 초기화에서 수행됩니다.ngOnInit

기본적으로을 사용할 수 있습니다 { static: false }. 동적 뷰를 작성 중이고 템플리트 참조 변수를 사용하려면 다음을 사용해야합니다.{ static: true}

자세한 내용은이 기사를 읽을 수 있습니다

실무 데모

데모에서는 템플릿 참조 변수를 사용하여 div로 스크롤합니다.

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

함께 { static: true }, 우리가 사용할 수 this.scrollTo.nativeElement있는 ngOnInit,하지만 함께 { static: false }, this.scrollTo될 것입니다 undefined에서 ngOnInit우리는 단지에에 액세스 할 수 있도록,ngAfterViewInit


답변

뷰 자식이 두 가지 인수를 요구하기 때문에

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

@ViewChild ( ‘amountInput’, {정적 : false,}) amountInputRef : ElementRef;


답변

Angular 8에서 ViewChild는 항상 2 개의 매개 변수를 취하고 두 번째 매개 변수에는 항상
정적 : true 또는 정적 : false가 있습니다.

다음과 같이 시도해보십시오.

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

또한 static: falseAngular 9의 기본 폴백 동작이 될 것입니다.

정적 거짓 / 참인 것 : 경험적으로 볼 때 다음을 수행 할 수 있습니다.

  • { static: true } ngOnInit에서 ViewChild에 액세스하려면 설정해야합니다.

    { static: false }ngAfterViewInit에서만 액세스 할 수 있습니다. 템플릿의 요소에 구조적 지시문 (예 : * ngIf)이있는 경우에도 원하는 결과입니다.


답변

IDEA를 통한 모든 교체를위한 정규식 (Webstorm으로 테스트)

찾기: \@ViewChild\('(.*)'\)

바꾸다: \@ViewChild\('$1', \{static: true\}\)


답변

다음과 같이 ViewChild에 두 번째 인수를 사용해야합니다.

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