I wonder if there is possibility to dynamically add ion-select-option to ion-select after axios promise returns number of options, for example if axios promise returns x=5 then add 5 oprions to already created ion-select.
Here is ion-select code (there is single ion-select-option):
<ion-item>
<ion-label>Some label</ion-label>
<ion-select class="some class" value="1" interface="popover">
<ion-select-option value="1">1</ion-select-option>
</ion-select>
</ion-item>
Here is axios function which is triggered on button click:
methods: {
onClickFunction(){
axios.post("http://some_php.php", formData)
.then(res => {
x = res.data[2]; // <-- this is number of options
// here I want to add x * ion-select-option
}
}
If anybody wonder, I found solution.
<ion-item>
<ion-label>Some label</ion-label>
<ion-select placeholder="1" v-model="selectedOption" interface="popover">
<ion-select-option v-for="(item, index) in tab" :key="index"
:value="item">{{item}}</ion-select-option>
</ion-select>
</ion-item>
data() {
return {
tab: []
},
created() {
onClickFunction(){
axios.post("http://some_php.php", formData)
.then(res => {
x = res.data[2];
for (let i = 1; i <= res.data[2]; i++){
this.tab.push(i);
}
}
}
This works as I expected.
Related
In my app, I have a list where the user can add to and delete elements from it. My problem is, when I click an element (it can be in the middle, at the end etc.), it deletes the first element of the list. And when I refresh the page, I can see the previously 'deleted' elements. Like I haven't deleted anything. Here is my code. What's wrong with it and how should I fix it?
HTML:
<button mat-icon-button>
<mat-icon (click)="deleteWorkItem(row)">block</mat-icon>
</button>
TS:
deleteWorkItem(row: IProduct, index: number) {
let supplierProduct: ISupplierProduct = {
Supplier: {
SupplierId: this.SupplierId
},
Product: {
ProductId: row.ProductId
}
};
this.confirmDialogRef = this._dialog.open(FuseConfirmDialogComponent, {
disableClose: false
});
this.confirmDialogRef.componentInstance.confirmMessage = 'Ürünü silmek istiyor musunuz?';
this.confirmDialogRef.afterClosed().subscribe(result => {
if (result) {
this._service.update('Supplier/DeleteSupplierProduct', supplierProduct).subscribe(response => {
this._customNotificationService.Show('Ürün silindi', 'Tamam', 2);
});
let tempData = this.dataSource.data.slice(0);
tempData.splice(index, 1);
this.dataSource = new MatTableDataSource(tempData);
this.EditIndex = undefined;
this._products = this.dataSource.data;
this.ProductChange.emit(this._products);
}
});
}
You don't seem to pass index into deleteWorkItem method.
You need to declare a template variable within *ngFor as follows:
<div *ngFor="let row of data; let i = index">
...
<button mat-icon-button>
<mat-icon (click)="deleteWorkItem(row, i)">block</mat-icon>
</button>
</div>
I have a select, where the user's servers are rendered. Each server has several security groups. I need to show the user on select, only the server that does not have that security group. However, in my select, it is repeating the name of the server for each different security group.
Example: I have the server test01 it has the security groups: novo09, default, relow.
When I select the security group hello01, I want to show the server test01 only once in select, and not 2 times, it is showing 2 times because I have 2 groups already included in server = novo09, relow.
server payload:
{id: "b9c7e32a-bf99-4250-83cb-13523f9c1604", name: "test01", flavor: {…}, securityGroups: [{name: 'relow'}, {name: 'Novo09'} ]}
My component code:
public selectedGroupName: string = '';
ngOnInit(): void {
let counter = 0;
forkJoin(
this.serverService.getServer(),
this.securityGroupService.getSecurityGroups())
.pipe(takeWhile(() => this.alive),
concatMap((data) => {
this.servers = data[0].map((item) => ({
...item,
securityGroups: this.serverService.getServerById(item.id)
.pipe(map(server => server["security_groups"]))
}))
this.securityGroups = data[1].map((item) => ({
...item,
expanded: false,
}))
return this.servers.map((server) => server.securityGroups);
}), concatMap(items => items))
.subscribe((data: any) => {
this.servers[counter].securityGroups = data.filter(group => group.name !== 'default');
counter++;
})
this.form = this.formBuilder.group({
server: new FormControl('')
})
}
public openAttachModal(content, securitGroupName: string) {
this.selectedGroupName = securitGroupName;
}
My Html code:
<ng-container *ngFor="let group of securityGroups">
<div class="user-info__basic">
<h5 class="mb-0">{{group.name}}</h5>
</div>
<button type="button" class="btn btn-primary" ngbTooltip="Attach Group" triggers="hover"
(click)="openAttachModal(attachModal, group.name)"><i class="fas fa-plus"></i></button>
</ng-container>
<ng-container *ngFor="let server of servers">
<ng-container *ngFor="let secGroup of server.securityGroups">
<ng-container *ngIf="secGroup.name !== selectedGroupName">
<option [value]="server.id">
{{server.name}}
</option>
</ng-container>
</ng-container>
<ng-container *ngIf="server.securityGroups.length == 0">
<option [value]="server.id">
{{server.name}}
</option>
</ng-container>
</ng-container>
image result of select
https://imgur.com/7K2G7HF
When the user selects the security group, you could trigger an event to extract the list of servers where that security group is not present. Something like:
const servers = servers.filter(server => !server.securityGroups.find(secGroup => secGroup.id === selectedSecurityGroup.id));
// Where selectedSecurityGroup is the security group the user selected
And you could avoid adding a server twice:
servers = servers.filter((server, index, self) => self.indexOf(server) === index);
This filter will keep only the first instance of each server.
How to get favourite item from list item app . i am using ionic 4 . my json data added localstorage but not get added data properly.
favourite.service.ts
getAllFavoriteItems(){
return this.storage.get("object");
}
isFavorite(favorite) {
return this.getAllFavoriteItems().then(result => {
return result && result.indexOf(favorite) !== -1;
});
}
favoriteItem(favorite) {
return this.getAllFavoriteItems().then(result => {
if (result) {
result.push(favorite);
return this.storage.set("object", result, );
} else {
return this.storage.set("object", [favorite]);
}
});
}
unfavoriteItem(favorite) {
return this.getAllFavoriteItems().then(result => {
if (result) {
var index = result.indexOf(favorite);
result.splice(index, 1);
return this.storage.set("object", result);
}
});
}
favourite.page.ts
ngOnInit() {
this.storage.get("object").then((ids) => {
console.log( 'favouriteIds' ,ids)
this.favouriteIds = ids;
})
// this.favouriteIds = this.favoriteService.getAllFavoriteItems();
// console.log('favitems',this.favitems)
}
favourite.page.html
<ion-content no-padding color="secondary">
<ion-list>
<div class="main">
<ion-item *ngFor="let item of favouriteIds" [routerLink]="['/','details',item.id]"
class="item-native" (click)="showInterstitial()">
<ion-thumbnail slot="start">
<img [src]="item.thumnailUrl">
</ion-thumbnail>
<ion-label>{{item.title}}</ion-label>
<ion-label>{{item.id}}</ion-label>
</ion-item>
</div>
</ion-list>
</ion-content>
full list item in screenshot
Favourite list item in this , but not get properly favourite item
You need to parse it to JSON, once you retrieve from local storage,
this.favouriteIds = JSON.parse(ids);
I want to push an array of inputs into a form. At the moment I always get with a console.logonly the latest inputted value. How can I push all the input values? I just wonder If I even need a additional form arrays. Since I can output the whole list in my console. So I have access to this data which is imported in order to upload to a server.
page.html
<form [formGroup]="form" (ngSubmit)="addTag(form.value)">
<ion-item>
<ion-input formControlName="tag" clearInput="true" placeholder="Tags" [(ngModel)]="tagInput" name="tagValue"></ion-input>
<ion-button item-right type="submit" icon-only>
<ion-icon name="checkmark"></ion-icon>
</ion-button>
</ion-item>
</form>
<ion-chip *ngFor="let tag of tagList; let i = index">
<ion-icon name="pricetag"></ion-icon>
<ion-label>{{ tag }}</ion-label>
<ion-icon name="close-circle" (click)="removeChip(i)"></ion-icon>
</ion-chip>
page.ts
form: FormGroup;
public tagList: any[] = [];
constructor() { }
addTag(formValue) {
if (this.tagInput !== '') { //no empty input
this.tagList.push(formValue.tagValue);
this.tagInput = '';
}
}
ngOnInit() {
this.form = new FormGroup({
tag: new FormControl(null, {
updateOn: 'submit',
validators: [Validators.required, Validators.maxLength(20), Validators.minLength(1)]
})
});
}
confirm() {
console.log(this.form);
}
so, based on your code, you actually have a form and an array of items added from the form... not sure why you need a form array or anything like that. Your fixed code could just be like this:
<form [formGroup]="form" (ngSubmit)="addTag()">
<ion-item>
<ion-input formControlName="tag" clearInput="true" placeholder="Tags" name="tagValue"></ion-input>
<ion-button item-right type="submit" icon-only>
<ion-icon name="checkmark"></ion-icon>
</ion-button>
</ion-item>
</form>
<ion-chip *ngFor="let tag of tagList; let i = index">
<ion-icon name="pricetag"></ion-icon>
<ion-label>{{ tag }}</ion-label>
<ion-icon name="close-circle" (click)="removeChip(i)"></ion-icon>
</ion-chip>
get rid of the mixing of reactive forms and template forms, and just call add tag, don't pass a value in.
form: FormGroup;
public tagList: any[] = [];
constructor() { }
addTag() { // properly access and reset reactive form values
const tagCtrl = this.form.get('tag');
if (tagCtrl.value) {
this.tagList.push(tagCtrl.value);
this.tagCtrl.reset(''); // reset() sets the value and resets validation
}
}
ngOnInit() {
this.form = new FormGroup({
tag: new FormControl(null, {
updateOn: 'submit',
validators: [Validators.required, Validators.maxLength(20), Validators.minLength(1)]
})
});
}
confirm() {
console.log(this.tagList); // just check your tagList instead of looking at the form
}
you're overthinking it here. a FormArray could be useful under some circumstances, like needing some complex validation / error message capability, or ability to edit tags after adding them, but if simple remove is all you need, you're over engineering this.
How to use form validation with API calls to check if data is correct? Whenever I enter this Signup page I got errors like:
Cannot read property 'put' of undefined
Cannot read property 'http' of undefined
Could you guide me what is wrong in my code?
HTML:
<ion-content padding>
<p *ngIf="submitAttempt" style="color: #ea6153;">Please fill out all details accurately.</p>
<ion-list inset>
<form [formGroup]="signupForm">
<ion-item>
<ion-input formControlName="userName" [(ngModel)]="userName" placeholder="UserName" type="text"></ion-input>
</ion-item>
<ion-item>
<ion-input formControlName="email" [(ngModel)]="email" placeholder="Email" type="email"></ion-input>
</ion-item>
<ion-item>
<ion-input formControlName="password" [(ngModel)]="password" placeholder="Password" type="password"></ion-input>
</ion-item>
</form>
<button ion-button block (click)="register()">Register</button>
</ion-list>
</ion-content>
And this is my TS file, this code is inside constructor:
this.signupForm = formBuilder.group({
userName: ['', Validators.compose([Validators.required, Validators.pattern('[a-zA-Z]*')]), this.authService.checkUserName],
email: ['', this.authService.checkEmail],
password: ['']
});
this.authService is a class with API calls, here is one of the call, seconds looks same just with different address:
checkUserName(control: FormControl): any {
return new Promise((resolve, reject) => {
let headers = new Headers();
headers.append('Content-Type', 'application/json');
this.http.put('http://localhost:63203/api/Customers/CheckIfUserExist', JSON.stringify(control.value), { headers: headers })
.subscribe((res) => {
resolve(res);
}, (err) => {
reject(err);
});
});
}
you should use array function to keep the original context.
this.signupForm = formBuilder.group({
userName: ['', Validators.compose([Validators.required, Validators.pattern('[a-zA-Z]*')]), () => this.authService.checkUserName()],
email: ['', () => this.authService.checkEmail()],
password: ['']
});