Home > Back-end >  How to Console multiple values without using template or Reactive Form
How to Console multiple values without using template or Reactive Form

Time:06-21

This is the sample code. please help me with consoling multiple values without using any forms

<input  placeholder="Text" #input>
<input  placeholder="Text" #input>
    
<div  (click)="onClick(input.value)">
   <button class='btn btn-dark'>Submit</button>
</div>

TS

onClick(value: any) {
  console.log(value);
}

CodePudding user response:

Add different local references to inputs and pass the values.

    <input  placeholder="Text" #input1>
    <input  placeholder="Text" #input2>
        
    <div  (click)="onClick(input1.value, input2.value)">
       <button class='btn btn-dark'>Submit</button>
    </div>
    
    TS 
    
     onClick(value1: any,value2: any) {
        console.log(value1, value2);
     }

CodePudding user response:

What form? is CSS class selector .form-control. If you wish to console log with a button, you can pass inputs values to the method as params. Though to reference the correct input each should have an unique name after hashtag #. We pass to method onClick() multiple params (the input's values), parse then as obj {} and we console log that obj.

Html

<input  placeholder="Text" #input1 />
<input  placeholder="Text" #input2 />

<div  (click)="onClick(input1.value, input2.value)">
  <button >Submit</button>
</div>

TS

  onClick(input1: any, input2: any) {
    console.log({input1, input2});
  }

Working example: https://stackblitz.com/edit/angular-ivy-jzoybi?file=src/app/app.component.html

CodePudding user response:

You can use the spread operator as a function parameter in this way on the TypeScript(TS) side, there is no change in the HTML side as pass the value to the function argument

Here on the HTML side, you can pass as many arguments you can pass

HTML Code

<input  placeholder="Text" #input1 />
<input  placeholder="Text" #input2 />
<input  placeholder="Text" #input3 />

<div  (click)="onClick(input1.value, input2.value, input3.value)">
  <button >Submit</button>
</div>

TypeScript Side

onClick(...inputValues: any) {
    console.log(inputValues);
  }

so in the TS side, you need to add only 3 dots in the function arguments, 3 dots represent as spread operator.

You can get it as an array of values you have passed from the HTML to the TS side.

Hope it will help it to use the modern javascript features.

  • Related