How to use angular-translate within a customer filter and re-translate on $translate.use() - angular-translate

I'm using a custom filter to translate the ng-options of a select element. The translate works fine UNTIL I use $translate.use() to change the language. I want the ng-options to be re-translated. Does anyone know how to do this?
This is my customer filter:
function translateAndFormatPhoneCountry(translateFilter) {
return function(phoneCountry) {
return translateFilter(phoneCountry.name) + " (" + phoneCountry.countryCode + ")";
};
}
And this is my select element:
phoneCountry will typically look like this:
{"name": "UNITED_KINGDOM", "countryCode": "+44"}

No worries, I got it sorted. See here for the guiding light: https://github.com/angular-translate/angular-translate/issues/134.
In the template:
ng-options="signup.translate.instant(phoneCountry.name) for phoneCountry in signup.model.phoneCountries"
In the controller, inject $translate then:
this.translate = $translate;

Related

How to make complex nested where conditions with typeORM?

I am having multiple nested where conditions and want to generate them without too much code duplication with typeORM.
The SQL where condition should be something like this:
WHERE "Table"."id" = $1
AND
"Table"."notAvailable" IS NULL
AND
(
"Table"."date" > $2
OR
(
"Table"."date" = $2
AND
"Table"."myId" > $3
)
)
AND
(
"Table"."created" = $2
OR
"Table"."updated" = $4
)
AND
(
"Table"."text" ilike '%search%'
OR
"Table"."name" ilike '%search%'
)
But with the FindConditions it seems not to be possible to make them nested and so I have to use all possible combinations of AND in an FindConditions array. And it isn't possible to split it to .where() and .andWhere() cause andWhere can't use an Object Literal.
Is there another possibility to achieve this query with typeORM without using Raw SQL?
When using the queryBuilder I would recommend using Brackets
as stated in the Typeorm doc: https://typeorm.io/#/select-query-builder/adding-where-expression
You could do something like:
createQueryBuilder("user")
.where("user.registered = :registered", { registered: true })
.andWhere(new Brackets(qb => {
qb.where("user.firstName = :firstName", { firstName: "Timber" })
.orWhere("user.lastName = :lastName", { lastName: "Saw" })
}))
that will result with:
SELECT ...
FROM users user
WHERE user.registered = true
AND (user.firstName = 'Timber' OR user.lastName = 'Saw')
I think you are mixing 2 ways of retrieving entities from TypeORM, find from the repository and the query builder. The FindConditions are used in the find function. The andWhere function is use by the query builder. When building more complex queries it is generally better/easier to use the query builder.
Query builder
When using the query build you got much more freedom to make sure the query is what you need it to be. With the where you are free to add any SQL as you please:
const desiredEntity = await connection
.getRepository(User)
.createQueryBuilder("user")
.where("user.id = :id", { id: 1 })
.andWhere("user.date > :date OR (user.date = :date AND user.myId = :myId)",
{
date: specificCreatedAtDate,
myId: mysteryId,
})
.getOne();
Note that depending on your used database the actual SQL that you use here needs to be compatible. With that could also come a possible draw back of using this method. You will tie your project to a specific database. Make sure to read up about the aliases for tables you can set if you are using relations this would be handy.
Repository
You already saw that this is much less comfortable. This is because the find function or more specific the findOptions are using objects to build the where clause. This makes is harder to implement a proper interface to implement nested AND and OR clauses side by side. There for (I assume) they have chosen to split AND and OR clauses. This makes the interface much more declarative and means the you have to pull your OR clauses to the top:
const desiredEntity = await repository.find({
where: [{
id: id,
notAvailable: Not(IsNull()),
date: MoreThan(date)
},{
id: id,
notAvailable: Not(IsNull()),
date: date
myId: myId
}]
})
I cannot imagin looking a the size of the desired query that this code would be very performant.
Alternatively you could use the Raw find helper. This would require you to rewrite your clause per field, since you will only get access to the one alias at a time. You could guess the column names or aliases but this would be very poor practice and very unstable since you cannot directly control this easily.
if you want to nest andWhere statements if a condition is meet here is an example:
async getTasks(filterDto: GetTasksFilterDto, user: User): Promise<Task[]> {
const { status, search } = filterDto;
/* create a query using the query builder */
// task is what refer to the Task entity
const query = this.createQueryBuilder('task');
// only get the tasks that belong to the user
query.where('task.userId = :userId', { userId: user.id });
/* if status is defined then add a where clause to the query */
if (status) {
// :<variable-name> is a placeholder for the second object key value pair
query.andWhere('task.status = :status', { status });
}
/* if search is defined then add a where clause to the query */
if (search) {
query.andWhere(
/*
LIKE: find a similar match (doesn't have to be exact)
- https://www.w3schools.com/sql/sql_like.asp
Lower is a sql method
- https://www.w3schools.com/sql/func_sqlserver_lower.asp
* bug: search by pass where userId; fix: () whole addWhere statement
because andWhere stiches the where class together, add () to make andWhere with or and like into a single where statement
*/
'(LOWER(task.title) LIKE LOWER(:search) OR LOWER(task.description) LIKE LOWER(:search))',
// :search is like a param variable, and the search object is the key value pair. Both have to match
{ search: `%${search}%` },
);
}
/* execute the query
- getMany means that you are expecting an array of results
*/
let tasks;
try {
tasks = await query.getMany();
} catch (error) {
this.logger.error(
`Failed to get tasks for user "${
user.username
}", Filters: ${JSON.stringify(filterDto)}`,
error.stack,
);
throw new InternalServerErrorException();
}
return tasks;
}
I have a list of
{
date: specificCreatedAtDate,
userId: mysteryId
}
My solution is
.andWhere(
new Brackets((qb) => {
qb.where(
'userTable.date = :date0 AND userTable.type = :userId0',
{
date0: dates[0].date,
userId0: dates[0].type,
}
);
for (let i = 1; i < dates.length; i++) {
qb.orWhere(
`userTable.date = :date${i} AND userTable.userId = :userId${i}`,
{
[`date${i}`]: dates[i].date,
[`userId${i}`]: dates[i].userId,
}
);
}
})
)
That will produce something similar
const userEntity = await repository.find({
where: [{
userId: id0,
date: date0
},{
id: id1,
userId: date1
}
....
]
})

How to display two column values in a single ag-grid cell?

I have a record of First_Name and Second_Name stored in MySql DB. Currently I am displaying it in 2 different columns of Ag-Grid. I need those data to be combined together as Name and to be displayed in Ag-Grid's single column. Please help!
I am using Vue.Js
You should use a valueGetter in your columnDef like this -
{
headerName: 'Name',
colId: 'name',
valueGetter: function(params) {
return params.data.First_Name + " " + params.data.Second_Name;
},
},
Example from docs here
The ans stated by Pratik is right. Maybe you can use arrow functions for valueGetter so that the code looks more concise and simplify function scoping.
{
headerName: 'Name',
valueGetter: params => {
return ${params.data.First_Name} ${params.data.Second_Name};
},
},

v-modal with a multi part variable

I'm not sure if this is the correct way to ask this, but I'm having trouble setting up a v-model that has multiple parts.
v-model="formInputs.input_ + inputType.id"
That would end up being this in the data:
data(){
return {
formInputs: {
input_(its id here): ''
//example input_5
},
}
},
Is it possible to chain values inside a v-model?
You can use [] instead of . as key accessor:
v-model="formInputs['input_' + inputType.id]"

Using Dynamic strings for querying nested mongo doc

I'm using the dot notation for querying a nested mongo doc. However I want this query to be dynamically generated.
For eg The nesting is as
{ "Car":
{
"Make":
{ "Model": "Some val"
Year : "Some year"
}
}
}
If I perform a query like db.carcoll.find({'Car.Make.Model':'some val'}) I get the results. However this query string 'Car.Make.Model' could change to be Car.Make.Year and I like this query to be dynamic.
I set it in a variable and try something like query='Car.Make' + choice;
where choice is a variable its either ".Model" or ".Year"
and run db.carcoll.find({query:"1989"})
I don't get the results in this case. How do I handle this
Not tested it, just thoughts. Did you tried this code:
var prop = "Car.Make." + "Model" //or ""Year"
var query = {};
query[prop] = "1989";
db.carcoll.find(query)

MongoDB like statement with multiple fields

With SQL we can do the following :
select * from x where concat(x.y ," ",x.z) like "%find m%"
when x.y = "find" and x.z = "me".
How do I do the same thing with MongoDB, When I use a JSON structure similar to this:
{
data:
[
{
id:1,
value : "find"
},
{
id:2,
value : "me"
}
]
}
The comparison to SQL here is not valid since no relational database has the same concept of embedded arrays that MongoDB has, and is provided in your example. You can only "concat" between "fields in a row" of a table. Basically not the same thing.
You can do this with the JavaScript evaluation of $where, which is not optimal, but it's a start. And you can add some extra "smarts" to the match as well with caution:
db.collection.find({
"$or": [
{ "data.value": /^f/ },
{ "data.value": /^m/ }
],
"$where": function() {
var items = [];
this.data.forEach(function(item) {
items.push(item.value);
});
var myString = items.join(" ");
if ( myString.match(/find m/) != null )
return 1;
}
})
So there you go. We optimized this a bit by taking the first characters from your "test string" in each word and compared the tokens to each element of the array in the document.
The next part "concatenates" the array elements into a string and then does a "regex" comparison ( same as "like" ) on the concatenated result to see if it matches. Where it does then the document is considered a match and returned.
Not optimal, but these are the options available to MongoDB on a structure like this. Perhaps the structure should be different. But you don't specify why you want this so we can't advise a better solution to what you want to achieve.