angulartypescript

Access const value assigned inside OnInit method on some event


I want to log name vale on click event but not able to. please advise. Inside .ts

export class ScrolldemoComponent implements OnInit {

      constructor() { }

      ngOnInit() {
        const name = "test";
      }

      myEvent(event) {
        console.log(name);
      }

    }

inside html

<button (click)="myEvent()">My Button</button>

Solution

  • Have it at the component level

    name:string = 'test'
     ngOnInit() {
        this.name = "test";
      }
    
      myEvent(event) {
        console.log(this.name);
      }