0

I am trying to access a value of my input field. here is sample code

<div>
    Test <input #test1 type="number" [value]='somevalue'/>
</div>
<div *ngIf='some-condition'>
    Test <input #test2 type="number" [value]='somevalue'/>
</div>

<span (click)="testData(test1,test2)">test<span>

Angular Code

testData(testa,testD)
{
    Console.log(testa);
    Console.log(testD);
} 

In above code, first div is working fine, but I am trying to do same thing in second div. It is giving me undefined value. I know something is missed.

if condition is false than it gives me undefined is fine, but when condition true is than also giving me undefined value.

Sangwin Gawande
  • 7,658
  • 8
  • 48
  • 66
Pravin Tukadiya
  • 489
  • 4
  • 20

2 Answers2

0

try this:-

<div>
    Test <input #test1 type="number" [value]='somevalue' (click)="testData(test1.value)"/>
</div>
<div *ngIf='some-condition'>
    Test <input #test2 type="number" [value]='somevalue' (click)="testData(test2.value)"/>
</div>

testData(testD)
{
    Console.log(testD);
} 

working example here with variable.value Working Example

Pardeep Jain
  • 84,110
  • 37
  • 165
  • 215
-1

You can use [hidden] instead of *ngIf. Variable declared inside *ngIf cannot be used outside it.

<div>
Test <input #test1 type="number" [value]='somevalue'/>
</div>
<div [hidden] ='somecondition'>
Test <input #test2 type="number" [value]='somevalue'/>
</div>

<span (click)="testData(test1.value,test2.value)">test</span>

Please refer this link for more clarification https://github.com/angular/angular/issues/6179

Vikash B
  • 945
  • 12
  • 26
  • Hidden doesn't have the same effect as *ngIf. NgIf removes the element completly from the dom, while hidden just uses css to hide an element. – Nightking Feb 13 '17 at 12:57