Angular 7 iterate json by button click - html

As I mentioned in title, I want to iterate by button click over my json response. See below my json file:
{
"id": 2,
"name": "Słownictwo",
"flashcardLists": [
{
"id": 17,
"frontside": "dasfasdv",
"backside": "csdascd"
},
{
"id": 18,
"frontside": "dsadsaad",
"backside": "sdasdadad"
},
{
"id": 19,
"frontside": "dasdsadd",
"backside": "sdaddsa"
}
]
}
FlashcardHTML:
<div class="flip-container" (click)="flip()" [class.flipped]="flipped" >
<mat-card-header></mat-card-header>
<mat-card-content *ngFor="let flashcard of flashcardLists" class="flipper">
<mat-card class="front">
{{flashcard.frontside}}
</mat-card>
<mat-card class="back">
{{flashcard.backside}}
</mat-card>
</mat-card-content>
</div>
I have component where in one time I want only one "frontside" and "backside".
Next, it will be replaced by button clicked which will increase counter but I don't know how to do that. I tried something like this flashcard[0].frontside, but it was KO. Maybe someone has encountered the same problem and can help me.
For all answers thanks in advance

If I understand properly, you wanna be flipping a single card.
Something like this should do:
<mat-card-content *ngFor="let flashcard of flashcardLists" class="flipper">
<mat-card [class.front]="!flashcards[i].isFlipped"
[class.back]="flashcards[i].isFlipped"
(click)="flashcards[i].isFlipped = !flashcards[i].isFlipped "
>
{{ flashcards[i].isFlipped ? flashcard.backside : flashcard.frontside }}
</mat-card>
</mat-card-content>
Just add this map of card states to y0our component:
flashcards: { [key: string]: boolean } = {};

You don't need an *ngFor in your mat-card-content, instead bind it to a flipCard variable, which will change on button iterate click. As for the front or back, use another variable isFront which you'll update on flip button click. something like this:
component.html:
<mat-card>
<mat-card-header></mat-card-header>
<mat-card-content class="flipper">
<div class="front" *ngIf="isFront">
{{flashcard.frontside}}
</div>
<div class="back" *ngIf="!isFront">
{{flashcard.backside}}
</div>
</mat-card-content>
<mat-card-actions>
<button (click)="iterate()" class="btn-flashcard" mat-button mat-raised-button id="previous">
Następna
</button>
<button mat-button (click)="flip()" [class.flipped]="flipped">LIKE</button>
<button mat-button>SHARE</button>
</mat-card-actions>
</mat-card>
component.ts:
flashcardList: any[] // use your flashCard class instead of any
flashcard: any; // use your flashCard class instead of any
isFront = true;
ngOnInit() {
// init first card
// flashcard = first card
}
iterate() {
// logic for getting the next card
// flashcard = next card
// e.g.
let index = this.flashcardList.indexOf(this.flashcard);
this.flashcard = this.flashcardList[index + 1];
}
flip() {
this.isFront = !this.isFront;
}

Related

Angular 9, how can I use a dynamic input field to get info from a list or array?

I need to get all the strings contained into Assignes array which is a property of Atm object and put them in all the dynamic input, one for each string giving opportunity of updating them or deleting.
How can i do by using FormArray?
atm: Atm; //has an array of string as property
get Assignes() {
return this.virtualForm.get('Assignes') as FormArray;
}
addAssigne() {
this.Assignes.push(this.formBuilder.group({ point: '' }));
}
deleteAssigne(index) {
this.Assignes.removeAt(index);
}
buildForm() {
this.form = new FormGroup({
model: new FormControl(this.atm.Model , Validators.required),
vendor: new FormControl(this.atm.Vendor , Validators.required),
Assignes : this.formBuilder.array([this.formBuilder.group({point : ''})]),
}
<div formArrayName="Assignes">
<div *ngFor="let item of Assignes.controls; let pointIndex=index" [formGroupName]="pointIndex">
<mat-form-field appearance="outline">
<mat-label>Assigne</mat-label>
<input matInput formControlName="point" [readonly]=!isAdmin placeholder="Assigne"/>
</mat-form-field>
<button color="primary" *ngIf="isAdmin" mat-raised-button (click)="deleteAssigne(pointIndex)">Delete assigne</button>
</div>
<button color="primary" *ngIf="isAdmin" mat-raised-button (click)="addAssigne()">Add assigne</button>
</div>
You can do that simply even without using formArray. You just need to run the for loop on the array and render the dynamic input fields.
The code should look like the below:
<div *ngFor="let item of atm; let pointIndex=index" >
<mat-form-field appearance="outline">
<mat-label>Assigne</mat-label>
<input matInput name="assigne{{i}}" [(ngModel)]="item" placeholder="Assigne"/>
</mat-form-field>
<button color="primary" *ngIf="isAdmin" mat-raised-button (click)="deleteAssigne(pointIndex)">Delete assigne</button>
</div>
<button color="primary" *ngIf="isAdmin" mat-raised-button (click)="addAssigne()">Add assigne</button>
The .ts file should get updated by:
atm: Atm; //has an array of string as property
addAssigne() {
this.atm.push('');
}
deleteAssigne(index) {
this.atm.splice(index,1);
}

Hovering over mat-card

How to show mat-card-action on hover over card. When i hover over one card it shows action for every card.
<mat-card (mouseover)="hover=true" (mouseleave)="hover=false" [className]="flashcard.privatno ? 'privatno' : 'javno'" *cdkVirtualFor = "let flashcard of flashcards; let i = index" (click)="loadOne(i)">
<mat-card-content>
<p>{{seci(flashcard.pitanje)}}</p>
</mat-card-content>
<mat-card-actions >
<button mat-button *ngIf="hover==true">LIKE</button>
</mat-card-actions>
[Hovering over first card. It should show only LIKE on that card and not on the other][1]
[1]: https://i.stack.imgur.com/36Bsp.png
When you say *ngIf="hover==true" you are comparing all the elements of the for loop with the same variable, that's why all will display/hide at the same time. You need a way to differentiate each element. If your flashcard item have an id, you can try something like this:
.html:
<mat-card (mouseover)="toggleHover(flashcard.id)" (mouseleave)="removeHover()" [className]="flashcard.privatno ? 'privatno' : 'javno'" *cdkVirtualFor = "let flashcard of flashcards; let i = index" (click)="loadOne(i)">
<mat-card-content>
<p>{{seci(flashcard.pitanje)}}</p>
</mat-card-content>
<mat-card-actions >
<button mat-button *ngIf="hoveredElement === flashcard.id ">LIKE</button>
</mat-card-actions>
</mat-card>
.ts
public hoveredElement:any;
toggleHover(id) {
this.hoveredElement = id
}
removeHover() {
this.hoveredElement = null;
}

Why mat-select clear the value in this reactive form?

I´m working on an app like google forms, we have a form with questions, we get these questions from an api and dynamically render the form. the problem is that when i want to add validation to the form with angular reactive forms, the mat-select stops working and every time i select a value, the select is clear.
I already try to adapt this https://medium.com/aubergine-solutions/add-push-and-remove-form-fields-dynamically-to-formarray-with-reactive-forms-in-angular-acf61b4a2afe with no luck
template
<mat-horizontal-stepper [linear]="true" #stepper style="background: transparent">
<mat-step *ngFor="let materia of materias;let m = index;" [stepControl]="createForm(materia.id)">
<ng-template matStepLabel>{{materia.descripcion}}</ng-template>
<form [formGroup]="getForm(materia.id)">
<div fxLayout="column" fxLayoutAlign="space-around stretch" fxLayoutGap="10px">
<div>
<mat-card *ngFor="let competencia of materia.competencias">
<mat-card-header>
<mat-card-title>{{competencia.nombre}}</mat-card-title>
</mat-card-header>
<mat-card-content>
<div fxLayout="column" fxLayoutGap="30px" formArrayName="{{createFormArray(materia.id,competencia.id)}}">
<div fxLayout="row">
<i>{{competencia.descripcion}}</i>
</div>
<div fxLayout="column" fxLayoutGap="2px">
<span *ngFor="let competenciaSimple of competencia.competenciasSimples; let i = index;" fxLayout="row">
<mat-form-field appearance="outline"
*ngIf="competenciaSimple !== null && competenciaSimple !== undefined" fxFlex>
<mat-select (selectionChange)="onSelected($event,competenciaSimple)"
[value]="getSelectedValue(competenciaSimple)" [formControl]="createControl(materia.id,competencia.id)" [id]="i">
<span *ngFor="let fase of competenciaSimple.fases">
<mat-option *ngFor="let conductaObservable of fase.conductasObservables"
[value]="conductaObservable">
{{conductaObservable.descripcion}}
</mat-option>
</span>
</mat-select>
</mat-form-field>
<!-- <input type="hidden" value="competenciaSimple" [(ngModel)]="calificacion.conductasObservables[i].competenciaSimple"/> -->
</span>
</div>
</div>
</mat-card-content>
</mat-card>
</div>
<div fxLayout="row">
<button mat-flat-button type="button" matStepperPrevious *ngIf="!isFirstPage" color="primary"
fxFlex="20">ANTERIOR</button>
<span fxFlex="80"></span>
<button mat-flat-button type="button" *ngIf="!isLastPage" color="primary" fxFlex="20">SIGUIENTE</button>
<button mat-flat-button type="button" (click)="onSubmit()" *ngIf="isLastPage" color="accent"
fxFlex="20">TERMINAR</button>
</div>
</div>
</form>
</mat-step>
</mat-horizontal-stepper>
component.ts
forms = new Array<FormGroup>();
getForm(index: number): FormGroup {
return this.forms[index];
}
createForm(index: number): FormGroup {
const form = this.formBuilder.group({});
this.forms[index] = form;
return form;
}
createFormArray(index: number, name: string): string {
const array = this.formBuilder.array([]);
const arrayName = `competencia_${name}`;
this.forms[index].addControl(arrayName, array);
return arrayName;
}
createControl(index: number, arrayName: string): FormControl {
const control = this.formBuilder.control(false);
const an = `competencia_${arrayName}`;
const array = (this.forms[index].get(an));
(array as FormArray).push(control);
return control;
}
getControlId(): string {
this.controlNumber += 1;
return this.controlNumber.toString()
}
The idea is to validate the mat-select as required so the stepper cant advance when no value is selected, that works if a add the Validator, but the mat-select doesn´t persist the value so if i remove the [formControl]="createControl(materia.id,competencia.id)" the mat-select work but no validation result.
There are several popular open source Angular Form Libraries (you can take a look at the source code and see how they dynamically add validation's to a control):
GitHub: ng-dynamic-forms
GitHub: ngx-formly
GitHub: angular-schema-form (AngularJS) - Generate forms from a JSON schema
GitHub: ngx-schema-form - HTML form generation based on JSON Schema
GitHub: angular2-json-schema-form - Angular 2 JSON Schema Form builder

Do different things in the same function depending on which html component called that function

I am making a basic toggle app in angular.I have two toggle buttons.I am displaying a message in toggle.I want to call the same function on toggle change but do different things depending on which button was toggled.Is it possible or do I have to use two different functions? Thanks in advance for the help.
Here is my template code:
<mat-card class="card" fxLayout="column" fxLayoutAlign="center center" >
<form class="example-form" [formGroup]="formGroup" (ngSubmit)="onFormSubmit()" ngNativeValidate>
<mat-action-list>
<mat-list-item > <mat-slide-toggle
(change)="onChange($event);displayMessage($event)" formControlName="Policy1" >
<span class="label">{{message}}</span></mat-slide-toggle></mat-list-item>
<mat-list-item > <mat-slide-toggle (change)="onChange($event)" formControlName="Policy2">Policy2</mat-slide-toggle></mat-list-item>
</mat-action-list>
<p>Form Group Status: {{ formGroup.status}}</p>
<button mat-raised-button [disabled]="disable" class="button" type="submit">Save Settings</button>
</form>
</mat-card>
The funtion that I'm calling from the toggle button:
displayMessage(e){
if(e.checked)
{
this.message = 'Toggled';
}
else
this.message = 'Slide';
}
The $event object from the (change) emitter has a srcElement that you can refer to when you want to find out which element caused the change.
If you want to retrieve the id of the element that called the function you do so with event.srcElement.id
You can pass more arguments to the handler:
<mat-slide-toggle *ngFor="let item of thingsToDo; let i = index"
(change)= "onToggle($event, item.id, i)">
onToggle = (event, id, indexInArray) => { //...

Angular: How to dynamically add components to parent Dashboard component?

I have two components. One is a dashboard of cards (created with ng generate #angular/material:material-dashboard --name=my-dashboard) where the cards are created like this:
<div class="grid-container">
<h1 class="mat-h1">Dashboard</h1>
<mat-grid-list cols="2" rowHeight="350px">
<mat-grid-tile *ngFor="let card of cards" [colspan]="card.cols" [rowspan]="card.rows">
<mat-card class="dashboard-card">
<mat-card-header>
<mat-card-title> {{card.title}}
<button mat-icon-button class="more-button" [matMenuTriggerFor]="menu" aria-label="Toggle menu">
<mat-icon>more_vert</mat-icon>
</button>
<mat-menu #menu="matMenu" xPosition="before">
<button mat-menu-item>Expand</button>
<button mat-menu-item>Remove</button>
</mat-menu>
</mat-card-title>
</mat-card-header>
<mat-card-content class="dashboard-card-content">
<div>{{ card.content }}</div>
</mat-card-content>
</mat-card>
</mat-grid-tile>
</mat-grid-list>
</div>
And is filled like that:
export class DashComponent {
cards = [
{ title: 'Character', cols: 2, rows: 1, content: '<app-character-sheet></app-character-sheet>' },
{ title: 'Card 2', cols: 1, rows: 1 },
{ title: 'Card 3', cols: 1, rows: 2 },
{ title: 'Card 4', cols: 1, rows: 1 }
];
}
I want to fill the cards with different components. But when I went and tried it like you can see above (with the content variable), the HTML didn't parse the selector. The card just hat the literal content: .
How can I dynamically fill my cards with components?
Cheers
If you really need to dynamically insert components, read this article.
Alternative solution is to use structural directives like ngIf or ngSwitchCase for the case where you have limited set of content options:
<mat-card-content class="dashboard-card-content">
<div *ngIf="card.content"><app-character-sheet></app-character-sheet></div>
</mat-card-content>
You can unsafely insert HTML without post processing (but it is not recommended):
<div [innerHTML]="card.content"></div>