app
app

Reputation: 207

translate dynamic string in angular 10 using ngx-translate

I am using some dynamic values to create a string and sending that to sweetalert config.

I was wondering is there any way we can translate the string before sending to config?

I had seen couple of solutions where we can pass variable to translate method but is there any other solutions can be used?

What should I add in en.json?

let status = '';
switch (action?.innerText) {
    case 'Accept': {
        status = 'Accepted';
        break;
    }
    case 'Approve': {
        status = 'Approved';
        break;
    }
    case 'Delete': {
        status = 'Deleted';
        break;
    }
    case 'Reject': {
        status = 'Rejected';
        break;
    }
}

//You have ${status} a Request for $${this.data?.details?.amount}
let transalteTitle;
this.translate.get('You have', {
    value: status
}, ' a Request for', {
    value: this.data?.details?.amount
}).subscribe(res => {
    transalteTitle = res;
});

const configval = {
    title: transalteTitle,
    text: 'Do you want to continue?',
    showCancelButton: true,
    icon: 'warning',
    confirmButtonText: 'YES',
    cancelButtonText: 'NO'
};


//en.json

{
    "title": "You have ${status} a Request for ${val}"
    "status_accepted": "accepeted",
    "status_rejected": "rejected"
}

Upvotes: 2

Views: 1204

Answers (1)

Amit Desai
Amit Desai

Reputation: 424

let status = '';
switch (action?.innerText) {
    case 'Accept': {
        status = 'status_accepted';
        break;
    }
    case 'Approve': {
        status = 'status_approve';
        break;
    }
    case 'Delete': {
        status = 'status_delete';
        break;
    }
    case 'Reject': {
        status = 'status_rejected';
        break;
    }
}

//You have ${status} a Request for $${this.data?.details?.amount}
let transalteTitle;
this.translate.get(status).pipe(switchMap(translatedStatus =>
    this.translate.get('title', {
        status: translatedStatus, val:
            this.data?.details?.amount
    }))).subcribe(translatedTilte => {
    const configval = {
        title: transalteTitle,
        text: 'Do you want to continue?',
        showCancelButton: true,
        icon: 'warning',
        confirmButtonText: 'YES',
        cancelButtonText: 'NO'
    };
})


//en.json

{
    "title": "You have ${status} a Request for ${val}"
    "status_accepted": "accepeted",
        "status_rejected": "rejected"
}`enter code here`

Upvotes: 2

Related Questions