Issue
I am trying to set the value for the property using this. But it is not working in angular 15. I am getting error message like below:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'AppComponent'. No index signature with a parameter of type 'string' was found on type
How to resolve this issue?
app.compomnent.ts:
export class AppComponent {
aUser = false;
bUser = false;
cUser = false;
arr = ['aUser', 'bUser', 'cUser'];
value: string;
changed(value) {
this.value = value;
this.arr.forEach((val) => {
if (val === value) {
this[val] = true; // getting error
} else {
this[val] = false; // getting error
}
});
}
}
Demo: https://stackblitz.com/edit/select-change-event-cxhzgy?file=app%2Fapp.component.ts
Solution
You need to modify your component and html next way:
Component
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
users = {
aUser : false,
bUser : false,
cUser : false
};
arr = ['aUser', 'bUser', 'cUser'];
value: string;
changed(value) {
this.value = value;
this.arr.forEach((val) => {
if (val === value) {
this.users[val] = true;
} else {
this.users[val] = false;
}
});
}
}
HTML
<select #sel (change)="changed(sel.value)">
<option value="aUser">A</option>
<option value="bUser">B</option>
</select>
<pre>Value: {{value}}</pre>
<div *ngIf="users.aUser"> A </div>
<div *ngIf="users.bUser"> B </div>
<div *ngIf="users.cUser"> C </div>
You need to incapsulate accessable objects if you want to call them via string property name.
Updated option for Angular 15+:
Component
import { CommonModule } from '@angular/common';
import { Component } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import 'zone.js';
@Component({
selector: 'app-root',
imports: [CommonModule],
standalone: true,
template: `
<select #sel (change)="changed(sel.value)">
<option value="{{arr[0]}}">A</option>
<option value="{{arr[1]}}">B</option>
<option value="{{arr[2]}}">C</option>
</select>
<pre>Value: {{value}}</pre>
<div *ngIf="users[arr[0]]"> A </div>
<div *ngIf="users[arr[1]]"> B </div>
<div *ngIf="users[arr[2]]"> C </div>
<div *ngFor="let item of users | keyvalue">
{{item.key}}:{{item.value}}
</div>
`,
})
export class App {
users: {[key: string]: boolean} = {
aUser : false,
bUser : false,
cUser : false
};
arr = ['aUser', 'bUser', 'cUser'];
value: string = '';
changed(value: string) {
this.value = value;
this.arr.forEach((val) => {
this.arr.forEach((val) => {
if (val === value) {
this.users[val] = true;
} else {
this.users[val] = false;
}
});
});
}
}
bootstrapApplication(App);
Application: https://stackblitz.com/edit/stackblitz-starters-nyrvpj?file=src%2Fmain.ts
Answered By - Jivopis
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.