Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

680
Views
Error angular @ViewChild(): se esperaban 2 argumentos, pero se obtuvo 1

Al intentar ViewChild, aparece el error. El error es "No se proporcionó un argumento para 'opts'".

Tanto @ViewChild está dando el 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: se esperaban 2 argumentos, pero se obtuvo 1.

over 4 years ago · Santiago Trujillo
11 answers
Answer question

0

Angular 8

En Angular 8, ViewChild tiene otro parámetro

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

Puedes leer más al respecto aquí y aquí

Angular 9 y Angular 10

En Angular 9 , el valor predeterminado es static: false , por lo que no es necesario proporcionar un parámetro a menos que desee usar {static: true}

over 4 years ago · Santiago Trujillo Report

0

es porque la vista infantil requiere dos argumentos, intente así

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

@ViewChild('cantidadEntrada', { static: false, }) cantidadEntradaRef: ElementoRef;

over 4 years ago · Santiago Trujillo Report

0

En Angular 8, ViewChild toma 2 parámetros

 @ViewChild(ChildDirective, {static: false}) Component
over 4 years ago · Santiago Trujillo Report

0

Eso también resolvió mi problema.

 @ViewChild('map', {static: false}) googleMap;
over 4 years ago · Santiago Trujillo Report

0

En Angular 8, ViewChild siempre toma 2 parámetros, y los segundos parámetros siempre tienen estático: verdadero o estático: falso

Puedes probar así:

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

Además, el static: false será el comportamiento alternativo predeterminado en Angular 9.

¿Qué son falsos/verdaderos estáticos? Por lo tanto, como regla general, puede optar por lo siguiente:

  • { static: true } debe establecerse cuando desee acceder a ViewChild en ngOnInit.

    Solo se puede acceder a { static: false } en ngAfterViewInit. Esto también es lo que desea buscar cuando tiene una directiva estructural (es decir, * ngIf) en su elemento en su plantilla.

over 4 years ago · Santiago Trujillo Report

0

En Angular 8, ViewChild toma 2 parámetros:

Prueba así:

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

Explicación:

{ estático: falso }

Si establece static false , el componente secundario SIEMPRE se inicializa después de la inicialización de la vista a tiempo para las funciones de devolución de llamada ngAfterViewInit/ngAfterContentInit .

{ estático: verdadero}

Si establece static true , la inicialización del componente secundario tendrá lugar en la inicialización de la vista en ngOnInit

De forma predeterminada, puede usar { static: false } . Si está creando una vista dinámica y quiere usar la variable de referencia de la plantilla, debe usar { static: true}

Para más información, puedes leer este artículo

Demostración de trabajo

En la demostración, nos desplazaremos a un div usando la variable de referencia de plantilla.

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

Con { static: true } , podemos usar this.scrollTo.nativeElement en ngOnInit , pero con { static: false } , this.scrollTo no estará undefined en ngOnInit , por lo que podemos acceder solo en ngAfterViewInit

over 4 years ago · Santiago Trujillo Report

0

deberías usar el segundo argumento con ViewChild así:

 @ViewChild("eleDiv", { static: false }) someElement: ElementRef;
over 4 years ago · Santiago Trujillo Report

0

Regex para reemplazar todo a través de IDEA (probado con Webstorm)

Buscar: \@ViewChild\('(.*)'\)

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

over 4 years ago · Santiago Trujillo Report

0

Utilizar esta

@ViewChild(ChildDirective, {estático: falso}) Componente

over 4 years ago · Santiago Trujillo Report

0

En Angular 8, ViewChild tiene otro parámetro

@ViewChild('nameInput', {estático: falso}) componente

Resolví mi problema como a continuación

@ViewChild(MatSort, {estático: falso}) ordenar: MatSort;

over 4 years ago · Santiago Trujillo Report

0

Prueba esto en angular 8.0:

 @ViewChild('result',{static: false}) resultElement: ElementRef;
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!