0

I have 3 divs and click event, I am using a variable and calling a function in each event. Now I have an array this.newarray = ["one", "two", "three"]; I want to match the elements from the array with variable. If its success need to show alert. I have commented statically but I need it from array element. Here is the code below https://stackblitz.com/edit/angular-jk3xsa?file=src%2Fapp%2Fapp.component.ts

app.component.html

<hello name="{{ name }}"></hello>
<p>
    Start editing to see some magic happen :)
</p>
<div (click)="click1()">Click1</div>
<div (click)="click2()">Click2</div>
<div (click)="click3()">Click3</div>

app.component.ts

import { Component, onInit } from "@angular/core";

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  name = "Angular";
  newarray: any;
  matchoutput: any;

  ngOninit() {
    this.matchoutput = "one";
    this.newarray = ["one", "two", "three"];
  }
  function1() {
    if (this.matchoutput == this.newarray.indexOf(this.matchoutput)) {
      alert("hello");
    }
    /*if (this.matchoutput == "one" || this.matchoutput == "two") {
      alert("hello");
    }*/
  }
  click1() {
    this.matchoutput = "one";
    this.function1();
  }
  click2() {
    this.matchoutput = "two";
    this.function1();
  }
  click3() {
    this.matchoutput = "three";
    this.function1();
  }
}
Nbody
  • 1,168
  • 7
  • 33
  • Does this answer your question? [How do I check if an array includes a value in JavaScript?](https://stackoverflow.com/questions/237104/how-do-i-check-if-an-array-includes-a-value-in-javascript) – Slim Oct 14 '20 at 12:03
  • Just answered to your question does it solve your problem? – JSmith Oct 14 '20 at 12:07

2 Answers2

0

You are comparing a string value with an index(number) in your function1().

If you want to check weather your newarray contains matchoutput then you can simply use includes method. Try:

if (this.newarray.includes(this.matchoutput)) {
      alert("hello");
 }
Iris
  • 1
-1

I'll try

  function1() {
    for (let i = 0; i < this.newArray.length; i++)
      if (this.newArray[i] === this.matchOutput){
        alert("hello");
        break;
      }
  }

or

 if(this.newArray.includes(this.matchOutput))
   alert('hello')

in your example you are comparing an index with a string value

you could also make use of an hashmap or a set

const hash = new Set(['one', 'two', 'three'])

  function1() {
    if (this.hash.has(this.matchOutput))
      alert('hello');
  }
JSmith
  • 4,519
  • 4
  • 29
  • 45