ngFor over a string

Hi Everyone,

I have a string I’d like to iterate over. Is there any way to make ngFor accomplish this?

    public _code: string;

    constructor(public _navCtrl: NavController, public _navParams: NavParams) {
        this._code = "8675309";
    }

I currently have to write:

<button ion-button outline color="dark">{{ _code[0] }}</button>
<button ion-button outline color="dark">{{ _code[1] }}</button>
<button ion-button outline color="dark">{{ _code[2] }}</button>
<button ion-button outline color="dark">{{ _code[3] }}</button>

but I’d like to do the following:

<button *ngFor="let c of _code" ion-button outline color="dark">{{ c }}</button>

Thanks,
Ryan

I don’t know a solution for iterating over a string in the template, but you could try this:

You could use the following in your .ts file:

public _code: string[];

    constructor(public _navCtrl: NavController, public _navParams: NavParams) {
        this._code = Array.from("8675309");
    }

And then in your template:

<button *ngFor="let c of _code" ion-button outline color="dark">{{ c }}</button>
2 Likes

Thanks @Nexi! Simple and elegant!