How to validate dynamic radio button in ionic 3 - html

I have a series of questions which have radio answer choices. I can't figure out how to use angular validation to require the user to select all answer before clicking save & next.
NOTE: Please note that click save & next button gets the next 5 question from the controller depending on what choice was made. It's basically a dynamic questionnaire. Below is my code.
<ion-content id="testmodeCont" >
<div class="midCont mrgn0" >
<form #f="ngForm" class="login">
<div class="formCont">
<div *ngIf = "questionCategory == 'Diabetes'">
<div class="boxInCont" *ngFor="let question of AllQuestions | slice:numberOfQuestionsToDisplay:numberOfQuestionsToleft; let i = index">
<div *ngIf="mLanguageFlag === 'English'" >
<div class="heading" *ngIf="question.QuestionType=='dropdown'||question.QuestionType=='radio'||question.QuestionType=='toggle'|| question.QuestionType=='multiselect' ">
Q. {{question.QuestionText}}
</div>
</div>
<div *ngIf="mLanguageFlag === 'English'">
<div class="row mrgnB20" *ngIf="question.QuestionType=='radio'">
<div>
<div class="quetxt">
<ion-list radio-group [ngModelOptions]="{standalone: true}" [(ngModel)]="AllGroupAnswers[i].ExpectedAnswerId" >
<ion-item class="opteach" *ngFor="let answer of question.ExpectedAnswers">
<ion-label class="radioBox fr">{{answer.Answer}}
</ion-label>
<ion-radio item-left [value]="answer.ExpectedAnswerId" (ionSelect)="ValueChanged(answer)">
</ion-radio>
</ion-item>
</ion-list>
</div>
</div>
</div>
</div>
<div *ngIf="mLanguageFlag === 'English'">
<ion-item class="row" *ngIf="question.QuestionType=='dropdown'">
<ion-select formControlName="option" okText="Okay" cancelText="Nah" placeholder= "{{'personal.select'|translate}}" interface = "alert">
<ion-option *ngFor="let answer of question.ExpectedAnswers" [value]="answer.Answer" (ionSelect)="ValueChanged(answer)">{{answer.Answer}}
</ion-option>
</ion-select>
</ion-item>
</div>
</div>
</div>
</div>
</form>
</div>
<div class ="testbtn">
<ion-grid>
<ion-row>
<ion-col align-self-center>
<button ion-button block color="button-color" class="prevBtn" type="submit" (click) = "previous()" *ngIf="previousState" >{{"Previous" | translate}}</button>
</ion-col>
<ion-col align-self-end>
<button ion-button block color="button-color" class="saveBtn" type="submit" (click) = "next()" *ngIf="isDataLoad" >{{"Save & Next" | translate}}</button>
</ion-col>
</ion-row>
</ion-grid>
</div>
ts file
import { Component } from '#angular/core';
import { NavController, NavParams, AlertController, ToastController } from 'ionic-angular';
import { UserService } from '../../providers/service/share';
import { Service } from '../../providers/service/service';
import { Functions } from '../../providers/service/functions';
import { Values } from '../../providers/service/values';
import { UtilService } from '../../providers/service/util';
import { FeedsPage } from '../feeds/feeds';
import { TestPage } from '../test/test';
#Component({
templateUrl: 'testmode.html',
})
export class TestmodePage {
questionCategory: any
ckeckedArray: any;
answersID: any;
userPrefernce: any;
AllQuestions: any;
edittest: any;
testQuestionList: any;
TestQuestions: any;
lifestyleAnswers: any;
AllGroupAnswers: any;
AllTestAnswer: any;
ShowlifeStyleSave: boolean = false;
ExpectedAnswers: any;
mLanguageSelect: any;
mLanguageClass: any;
mLanguageFlag: any;
mLanguageClassdisc: any;
mLanguageClassWhite: any;
mLanguageClassGreen: any;
success: any;
numberOfQuestionsToDisplay: any;
numberOfQuestionsToleft: any
previousState: boolean = false;
isDataLoad: boolean = false;
pageIndex: any;
testform: FormGroup;
constructor(public navCtrl: NavController,public alertCtrl: AlertController,private toastCtrl: ToastController, public navParams: NavParams, public functions: Functions, public values: Values, public utilServices: UtilService, public userService: UserService, public service: Service) {
this.numberOfQuestionsToDisplay = 0;
this.numberOfQuestionsToleft = 5;
this.questionCategory = this.navParams.get('questionCategory')
this.mLanguageFlag = 'English';
this.testQuestionList = [];
this.TestQuestions = [];
this.lifestyleAnswers = [];
this.AllGroupAnswers = [];
this.AllTestAnswer = [];
this.ExpectedAnswers = [];
this.AllQuestions = [];
this.pageIndex = 0 ;
console.log(this.questionCategory);
this.setTestInfo();
}
ionViewDidLoad(){
this.mLanguageSelect = this.userService.getLocaleDisplayName();
console.log(this.mLanguageSelect)
if(this.mLanguageSelect == 'english'){
this.mLanguageClass = ' ';
this.mLanguageFlag='English';
this.mLanguageClassWhite = ' ';
this.mLanguageClassGreen = ' ';
}else if(this.mLanguageSelect == 'hindi'){
this.mLanguageClass = 'heading2';
this.mLanguageClassWhite = 'heading3';
this.mLanguageFlag='Hindi';
this.mLanguageClassGreen = 'heading4';
}
}
setTestInfo(){
var url = '/api/JM_TestQuestions?userId=1002&questionCategory='+ this.questionCategory ;
this.service.jivaGetMethod('1234567899','mobile',url).then((results) => {
console.log(results);
this.userService.setLifeStyleInfo(results);
this.edittest = this.userService.getLifeStyleInfo();
console.log("Your question",this.edittest);
this.AllQuestions = this.edittest.TestQuestions;
console.log("Your answer", this.AllQuestions);
for (var i = 0; i < this.AllQuestions.length; i++) {
// console.log("hello", this.AllQuestions[i]);
var obj= this.AllQuestions[i]
this.AllTestAnswer[i] = obj.ExpectedAnswers;
console.log(this.AllTestAnswer[i]+ i);
this.TestQuestions.push(obj);
console.log(this.TestQuestions.push(obj));
if (obj.ExpectedAnswers[0].UserAnswer==true){
this.AllGroupAnswers.push(obj.ExpectedAnswers[0]);
}else if(obj.ExpectedAnswers[1].UserAnswer==true){
this.AllGroupAnswers.push(obj.ExpectedAnswers[1]);
}else {
this.AllGroupAnswers.push({});
}
console.log("working");
this.testQuestionList.push(obj);
this.isDataLoad = true;
}
})
.catch((error)=>{
console.log(error);
})
}
ValueChanged(answer){
console.log(answer);
console.log(this.AllQuestions) ;
for (var i = 0; i < this.AllQuestions.length; i++) {
if (this.AllQuestions[i].QuestionId==answer.QuestionId) {
for (var j = 0; j < this.AllQuestions[i].ExpectedAnswers.length; j++) {
console.log(this.AllQuestions[i].ExpectedAnswers[j].Answer);
if (this.AllQuestions[i].ExpectedAnswers[j].ExpectedAnswerId==answer.ExpectedAnswerId) {
console.log('match-->',this.AllQuestions[i].ExpectedAnswers[j].ExpectedAnswerId,'-------',answer.ExpectedAnswerId);
this.AllQuestions[i].ExpectedAnswers[j].UserAnswer=true;
console.log(this.AllQuestions[i].ExpectedAnswers[j]);
}else {
console.log('not match-->',this.AllQuestions[i].ExpectedAnswers[j].ExpectedAnswerId,'-------',answer.ExpectedAnswerId);
this.AllQuestions[i].ExpectedAnswers[j].UserAnswer=false;
}
}
break;
}
}
}
submitTest(){
console.log(this.testQuestionList);
var TestQuestions = this.testQuestionList ;
var testData = {
"User": {
"UserId": 79163,
"FirstName": null,
"LastName": null,
"MobileNo": null,
"EmailId": null,
"UserSfdcId": null,
"FacebookId": null,
"GooglePlusId": null,
"AccessToken": null,
"AuthType": null,
"UserLanguage": null,
"UserDeviceId": null,
"UserPersonalDetails": null,
"CountryCode": 0
},
"TestQuestions": TestQuestions
};
this.functions.presentLoading(this.values.lan.WaitTitle);
// var identity = this.userService.getUserIdentity();
// var authtype = this.userService.getUserData().AuthType;
var url = 'http:///api/JM_TestQuestions';
this.service.submitSetUser1('1234567899','mobile',url,JSON.stringify(testData)).then((results) => {
console.log(results);
this.success = results
console.log(this.success);
this.functions.dismissLoading();
//this.navCtrl.setRoot(TestresultsPage);
}) .catch((error)=> {
alert("Please try after sometime..");
this.functions.dismissLoading();
})
}
next(){
this.previousState = true;
console.log(this.AllQuestions.length)
console.log(this.numberOfQuestionsToleft)
if(this.AllQuestions.length > this.numberOfQuestionsToleft) {
this.pageIndex++;
console.log(this.pageIndex)
this.numberOfQuestionsToDisplay = this.numberOfQuestionsToDisplay +5;
this.numberOfQuestionsToleft = this.numberOfQuestionsToleft + 5;
console.log(this.numberOfQuestionsToDisplay);
console.log(this.numberOfQuestionsToleft);
this.submitTest();
} else {
this.submitTest();
let toast = this.toastCtrl.create({
message: 'Your answer for ' + this.questionCategory + ' test was saved successfully',
duration: 2000,
position: 'top'
});
toast.onDidDismiss(() => {
console.log('Dismissed toast');
});
toast.present();
this.navCtrl.setRoot(FeedsPage);
}
}
previous() {
this.pageIndex--;
console.log(this.pageIndex)
this.numberOfQuestionsToDisplay = this.numberOfQuestionsToDisplay - 5;
this.numberOfQuestionsToleft = this.numberOfQuestionsToleft - 5;
console.log(this.numberOfQuestionsToDisplay);
console.log(this.numberOfQuestionsToleft);
this.submitTest();
if(this.pageIndex == 0){
console.log(this.pageIndex)
this.previousState = false;
}
}
ionViewWillLeave(){
let alert = this.alertCtrl.create({
title: "Jiva Ayurveda",
message: "Do you want to close the test ?",
buttons:[
{
text:"Yes",
handler: () => {
this.navCtrl.setRoot(TestPage);
}
},
{
text:"No",
handler: () => {
}
}
]
});
alert.present();
}
}

You can use a (click)=function(arg1, arg2) in order to create a function to check the specific validation you need to see happening.
Edit:
In the function you call with (click) add a logic at the beginning:
function(arg1) {
if(!arg1){
return; // eventually output a string in an error message to indicate the user needs to input or tick a box
} else {
// next page
}
}

use formgroup and initialize form like
this.loginForm = this.fb.group({
username: ['', Validators.required],
password: ['', Validators.required]
})

Related

list of Mat-Icon when change one all changes Angular 12

enter image description here
import { Component, OnInit,ViewChild, Input, Output, EventEmitter, ViewEncapsulation } from '#angular/core';
import { LoginService } from 'src/app/services/login.service';
import Swal from 'sweetalert2';
import { NgxSpinnerService } from 'ngx-spinner';
import { MatTableDataSource } from '#angular/material/table';
import { MatPaginator } from '#angular/material/paginator';
import { MatDialog } from '#angular/material/dialog';
import { MatSnackBar } from '#angular/material/snack-bar';
import { FormBuilder, FormGroup, NgForm, Validators, FormArray, FormControl } from '#angular/forms';
#Component({
selector: 'app-historique',
templateUrl: './historique.component.html',
styleUrls: ['./historique.component.css'],
encapsulation: ViewEncapsulation.Emulated
})
export class HistoriqueComponent implements OnInit
{
// #Input('rating') public rating: number[] = [];
// #Input('starCount') public starCount: number = 5;
#Input('color') public color: string = 'accent';
#Output() public ratingUpdated = new EventEmitter();
public snackBarDuration: number = 2000;
public ratingArr : number[] = [];
Questions: any = [];
listDeReponses: any[] = [];
starCount: number = 5;
rating: number = 0;
etoile: string='star_border';
selectedRow :any;
myForm = new FormGroup({
bouton: new FormControl('', [Validators.required]),
// icon: new FormControl('', [Validators.required])
});
constructor(private _loginService: LoginService,public spinner: NgxSpinnerService,public dialog: MatDialog,public snackBar: MatSnackBar) { }
ngOnInit(): void
{
// console.log("a "+this.starCount)
for (let index = 1; index <= this.starCount; index++)
{
this.ratingArr.push(index);
}
var mat = localStorage.getItem('matricule');
var matricule1 = mat!.replace('"', '');
var matricule = matricule1.replace('"', '');
var for1 = localStorage.getItem('formation');
var form = for1!.replace('"', '');
var formation = form.replace('"', '');
this._loginService.GetQuestionsByFormation(matricule,Number(formation)).subscribe(
data =>
{
this.Questions = data;
});
}
onClick(rating:number, quest: number) //
{
this.rating = rating;
console.log(rating);
this.snackBar.open('You rated ' + this.rating + ' / ' + this.starCount, '', {
duration: this.snackBarDuration
});
// this.ratingUpdated.emit(this.rating);
// // this.listDeReponses.push(quest,rating);
// console.log(this.listDeReponses);
return false;
}
showIcon(i: number) //,index:any
{
// this.selectedRow =i;
// console.log(index);
if (this.rating >= i + 1) {
return 'star';
} else {
return 'star_border';
}
}
}
export enum StarRatingColor
{
primary = "primary",
accent = "accent",
warn = "warn"
}
<li *ngFor="let quest of Questions">
<button mat-icon-button [color]="color" *ngFor="let ratingId of ratingArr;index as i" [id]="'star_'+i" (click)="onClick(i+1,3)" matTooltip="ratingId+1" matTooltipPosition="above">
<mat-icon *ngIf="this.etoile=='star_'+i">
{{showIcon(i)}}
</mat-icon>
</button>
<br>
<br>
<button mat-icon-button [color]="color" *ngFor="let ratingId of ratingArr;index as i" [id]="'star_'+i" (click)="onClick(i+1,2)" matTooltip="ratingId+1" matTooltipPosition="above">
<mat-icon *ngIf="this.etoile=='star_'+i" >
{{ showIcon(i) }}
</mat-icon>
</button>
</li>
I have a list of buttons with mat-icon inside, so when a want to change one of them they change all
I expect to change only the button I want to change
there is code html and typescript, hope it will help to understand
I have a list of buttons with mat-icon inside, so when a want to change one of them they change all
I expect to change only the button I want to change
there is code html and typescript, hope it will help to understand

the value 0 is displayed in an input, how to remove it?

I would like to remove the value 0 in the field Fiscal Year
illustration
search-dta.ts
export class SearchDta {
registreNational: number;
fiscalYear: number;
country: number;
constructor(
registreNational: number = 0,
fiscalYear: number = 0,
country: number = 0,
) {
this.registreNational = registreNational;
this.fiscalYear = fiscalYear;
this.country = country
}
}
search-dta.component.html
<div class="row row-cols-3 pt-3">
<div class="col text-end">
<label for="fiscalYear" class="form-label">Fiscal Year</label>
</div>
<div class="col-4">
<input id="fiscalYear" name="fiscalYear" type="text" class="form-control" name="fiscalYear"
style="min-width: 380px" [(ngModel)]="search.fiscalYear" maxlength="10">
</div>
</div>
search-dta.component.ts
export class SearchDtaComponent implements OnDestroy {
private unsubscribe$ = new Subject < void > ();
#Input() mode: string = "";
#Input() title: string = "";
#Input() canSelectAllTitles: boolean = false;
#Input() showWarnings: boolean = false;
#Input() disabledSvm: number[] = [];
#Input() saveState: Observable < string > = new Observable < string > ();
#Input() url: string = '';
#Input() from ? : string;
isModal: boolean = false;
markets$ = this.service.markets$;
search: SearchDta = new SearchDta();
data ? : SearchDtaResponse;
countries: Country[] = [];
#Output() selectedPersonnePhysiqueDta = new EventEmitter < PersonnePhysiqueDta | undefined > ();
#Output() changedState = new EventEmitter < SearchDta > ();
constructor(private service: SearchDtaService, private modalService: BsModalService, private router: Router) {}
ngOnInit() {
this.saveState.subscribe((url) => localStorage.setItem(url + '.search', JSON.stringify(this.search)));
const search = localStorage.getItem(this.url + '.search');
if (search) {
this.search = JSON.parse(search);
localStorage.removeItem(this.url + '.search')
}
this.service.getPaysDta().pipe(
takeUntil(this.unsubscribe$)
).subscribe((countries) => this.countries = countries);
}
ngOnDestroy(): void {
this.unsubscribe$.next();
this.unsubscribe$.complete();
}
submit(): void {
if (!this.isModal) {
const modalRef = this.modalService.show(SearchDtaResultModalComponent, {
...SEARCH_TITLE_MODAL_OPTIONS,
initialState: {
title: this.title,
isLoading: true,
disabledSvm: this.disabledSvm,
showWarnings: this.showWarnings
}
});
modalRef.content!.selectedPersonnePhysiqueDta.pipe(
takeUntil(this.unsubscribe$)
).subscribe((val: PersonnePhysiqueDta | undefined) => {
this.selectPersonnePhysiqueDta(val);
if (this.mode === 'create') {
this.router.navigate([
"/dta/create/" +
val?.NUMEROREGISTRENATIONAL +
"/" +
this.search.country +
"/" +
this.search.fiscalYear
]);
} else if (this.mode === 'delete') {
this.router.navigate([
"/dta/delete/" +
val?.NUMEROREGISTRENATIONAL +
"/" +
this.search.country +
"/" +
this.search.fiscalYear
]);
} else {
this.router.navigate([
"/dta/follow-up/" +
val?.NUMEROREGISTRENATIONAL +
"/" +
this.search.country +
"/" +
this.search.fiscalYear
]);
}
modalRef?.hide();
});
this.searchDta(true).pipe(
takeUntil(modalRef.content!.selectedPersonnePhysiqueDta)
).subscribe(res => {
if (modalRef) {
modalRef.content!.isLoading = false;
modalRef.content!.personnePhysique = res.DTA.PP;
if (!res.DTA.PP) {
modalRef.hide();
}
}
});
} else {
this.searchDta(false).pipe(
takeUntil(this.unsubscribe$)
).subscribe(res => {
this.data = res;
});
}
}
private searchDta(hideLoading: boolean): Observable < SearchDtaResponse > {
return this.service.searchDta(this.search, hideLoading).pipe(
takeUntil(this.unsubscribe$)
);
}
selectPersonnePhysiqueDta(personnePhysiqueDta: PersonnePhysiqueDta | undefined = undefined): void {
this.selectedPersonnePhysiqueDta.emit(personnePhysiqueDta);
}
changeState(): void {
this.changedState.emit(this.search);
}
}
How can I remove the 0?
Thank you very much
Try this:
in .ts
registreNational:number|undefined;
fiscalYear number|undefined ;
country: number |undefined
;
and add in html
<div class="col-4" *ngIf="search.fiscalYear>
<input id="fiscalYear" name="fiscalYear" type="text" class="form-control" name="fiscalYear" style="min-width: 380px" [(ngModel)]="search.fiscalYear" maxlength="10">
</div>
you're setting fiscalYear to 0 and binding that value to the input. you need to not set it to 0 if you don't want it to show 0
export class SearchDta {
constructor(
public registreNational: number = 0,
public fiscalYear: number | null = null,
public country: number = 0,
) {
}
}

How can I remove items from a list of tasks in Angular?

I'm creating a scheduler in which I can add tasks I've done in a certain amount of time. The tasks get added in a to-do list-like manner.
I'm trying to remove individual items from a list both from the front-end and from LocalStorage but I haven't found a solution that works yet. The function I'm trying to make work is "RemoveTask()".
Here's my code:
HTML:
<div class="modalbox" [class.active]="modalboxActive">
<div class="modal">
<p>What did you do?</p>
<input type="text" [(ngModel)]="activity.name" maxlength="22" />
<button (click)="addTask()" [disabled]="activity.name === ''">OK</button>
</div>
</div>
<div class="boxSuper">
<div class="boxLeft">
<div class="containerUp">
<button id="start" (click)="startTimer()">START</button>
<button id="pause" (click)="pauseTimer()">PAUSE</button>
<button id="stop" (click)="stopTimer()">STOP</button>
<button (click)="removeAll()">REMOVE ALL</button>
</div>
<div class="containerDown">
<p>{{ display }}</p>
</div>
</div>
<div class="boxRight">
<div class="containerLeft">
<ul class="listElementLeft" *ngFor="let item of tasks">
<div class="card">
<ul class="order">
<li class="list-group-item"><span>START:</span>{{ item.start }}</li>
<li class="list-group-item"><span>END:</span>{{ item.end }}</li>
<li class="list-group-item">
<span>LENGTH:</span>{{ item.length }}
</li>
</ul>
<div class="subcard">
<li>
{{ item.name }}
</li>
</div>
<div class="buttonCard">
<button (click)="removeTask(item.id)">REMOVE</button>
</div>
</div>
</ul>
</div>
</div>
</div>
TS:
import { importExpr } from '#angular/compiler/src/output/output_ast';
import { Component, OnInit } from '#angular/core';
import { timer } from 'rxjs';
import { Activity } from '../activity';
import { Result } from '../result';
#Component({
selector: 'app-timer',
templateUrl: './timer.component.html',
styleUrls: ['./timer.component.scss'],
})
export class TimerComponent implements OnInit {
ngOnInit() {
this.tasks = JSON.parse(localStorage.getItem('token') ?? '');
}
time: number = 0;
display: string | undefined;
interval: any;
modalboxActive = false;
startTime: string | undefined;
endTime: string | undefined;
id: number | undefined;
activity: Activity = {
name: '',
};
tasks: Result[] = [];
startFunc() {
this.startTime = new Date().toString().split(' ')[4];
}
endFunc() {
this.endTime = new Date().toString().split(' ')[4];
}
//task actions
addTask() {
var el: Result = {
id: this.id!,
name: this.activity.name,
end: this.endTime,
start: this.startTime,
length: this.display,
};
this.tasks.push(el);
localStorage.setItem('token', JSON.stringify(this.tasks));
this.activity.name = '';
this.modalboxActive = false;
this.resetTimer();
}
removeAll() {
localStorage.clear();
}
removeTask(id: number) {
// this.tasks.splice(id, 1);
this.tasks = this.tasks.filter((item) => item.id !== id);
}
//timer actions
startTimer() {
console.log('go');
this.interval = setInterval(() => {
if (this.time === 0) {
this.time++;
} else {
this.time++;
}
this.display = this.transform(this.time);
}, 1000);
this.startFunc();
}
transform(value: number): string {
var sec_num = value;
var hours = Math.floor(sec_num / 3600);
var minutes = Math.floor((sec_num - hours * 3600) / 60);
var seconds = sec_num - hours * 3600 - minutes * 60;
return hours + ':' + minutes + ':' + seconds;
}
pauseTimer() {
clearInterval(this.interval);
}
stopTimer() {
console.log('show');
this.modalboxActive = true;
clearInterval(this.interval);
this.endFunc();
}
resetTimer() {
console.log('reset');
this.time = 0;
}
}
Result interface:
export interface Result {
id: number;
start: string | undefined;
end: string | undefined;
length: string | undefined;
name: string | undefined;
}
It looks like when you add an item in task list, the task.id is always undefined. You need to give it an unique id in order to identify it on removal.
Try to change the following code:
from:
ngOnInit() {
this.tasks = JSON.parse(localStorage.getItem('token') ?? '');
}
// task actions
addTask() {
var el: Result = {
id: this.id!, // always is undefined
name: this.activity.name,
end: this.endTime,
start: this.startTime,
length: this.display,
};
this.tasks.push(el);
localStorage.setItem('token', JSON.stringify(this.tasks));
this.activity.name = '';
this.modalboxActive = false;
this.resetTimer();
}
removeAll() {
localStorage.clear();
}
removeTask(id: number) {
// this.tasks.splice(id, 1);
this.tasks = this.tasks.filter((item) => item.id !== id);
}
to:
ngOnInit() {
this.tasks = JSON.parse(localStorage.getItem('token')) ?? [];
}
// task actions
addTask() {
var el: Result = {
id: this.tasks.length + 1,
name: this.activity.name,
end: this.endTime,
start: this.startTime,
length: this.display,
};
this.tasks.push(el);
localStorage.setItem('token', JSON.stringify(this.tasks));
this.activity.name = '';
this.modalboxActive = false;
this.resetTimer();
}
removeAll() {
this.tasks = [];
localStorage.removeItem('token');
}
removeTask(id: number) {
this.tasks = this.tasks.filter((item) => item.id !== id);
localStorage.setItem('token', JSON.stringify(this.tasks)); // also, update localStorage
}
You can check a working example here.

How to reset timer I've created in Angular on click?

I'm creating a small app which keeps track of what activity I've done in a certain timespan once I write down said activity inside of an input field, once I click "OK" it should appear in a list.
I'm stuck on how I should proceed to reset the timer once I click the "OK" button, so basically what I should add inside the "resetTimer()" function which is supposed to trigger each time I add a task in a list.
HTML:
<div class="modalbox" [class.active]="modalboxActive">
<div class="modal">
<p>What did you do?</p>
<input type="text" [(ngModel)]="activity.name" />
<button (click)="addTask()" [disabled]="activity.name === ''">OK</button>
</div>
</div>
<div class="boxSuper">
<div class="boxLeft">
<div class="containerUp">
<button id="start" (click)="startTimer()">START</button>
<button id="pause" (click)="pauseTimer()">PAUSE</button>
<button id="stop" (click)="stopTimer()">STOP</button>
</div>
<div class="containerDown">
<p>{{ display }}</p>
</div>
</div>
<div class="boxRight">
<div class="containerLeft"></div>
<div class="containerRight">
<ul class="listElement" *ngFor="let item of tasks">
<li>
Activity:
<span>{{ item.name }}</span>
Length:
<span>{{ item.length }}</span>
</li>
</ul>
</div>
</div>
</div>
TS:
import { importExpr } from '#angular/compiler/src/output/output_ast';
import { Component, OnInit } from '#angular/core';
import { timer } from 'rxjs';
import { Activity } from '../activity';
import { Result } from '../result';
#Component({
selector: 'app-timer',
templateUrl: './timer.component.html',
styleUrls: ['./timer.component.css'],
})
export class TimerComponent implements OnInit {
ngOnInit() {}
time: number = 0;
display: string | undefined;
interval: any;
modalboxActive = false;
activity: Activity = {
name: '',
};
tasks: Result[] = [];
addTask() {
var el: Result = {
name: this.activity.name,
end: '',
start: '',
length: this.display,
};
this.tasks.push(el);
this.activity.name = '';
this.modalboxActive = false;
this.resetTimer();
}
resetTimer() {
console.log('reset');
}
startTimer() {
console.log('go');
this.interval = setInterval(() => {
if (this.time === 0) {
this.time++;
} else {
this.time++;
}
this.display = this.transform(this.time);
}, 1000);
}
transform(value: number): string {
var sec_num = value;
var hours = Math.floor(sec_num / 3600);
var minutes = Math.floor((sec_num - hours * 3600) / 60);
var seconds = sec_num - hours * 3600 - minutes * 60;
return hours + ':' + minutes + ':' + seconds;
}
pauseTimer() {
clearInterval(this.interval);
}
stopTimer() {
this.modalboxActive = true;
clearInterval(this.interval);
console.log('show');
}
}
Result interface:
export interface Result {
start: string | undefined;
end: string | undefined;
length: string | undefined;
name: string | undefined;
}
If you are trying to just reset it back to 0, all you would need to do is:
resetTimer(){
this.time = 0;
}

initialize ion-select with data from a JSON in IONIC

I am trying to fill a ion-select in IONIC from data that i get from my backend at the start of the application. This is the JSON i recive:
[{"codRole":15,"codEvent":43},{"codRole":15,"codEvent":45}]
And this is the ion-select:
[
The code:
import {Component,} from '#angular/core';
import {IonicPage, NavController, NavParams} from 'ionic-angular';
import {ZEUS_URL} from "../../properties/properties";
import {Http} from '#angular/http';
import {Rol} from "../../models/Rol";
import {Evento} from "../../models/Evento";
import {RolEvento, RolEventoJSON} from "../../models/RolEvento";
import {FormBuilder, FormControl, FormGroup} from "#angular/forms";
/**
* Generated class for the RolePage page.
*
* See http://ionicframework.com/docs/components/#navigation for more info
* on Ionic pages and navigation.
*/
#IonicPage()
#Component({
selector: 'page-role',
templateUrl: 'role.html',
})
export class RolePage {
AMform: FormGroup;
Name = new FormControl("");
roles: Rol[];
eventos: Evento[];
rolEventos: RolEvento[];
rolAdmin: boolean = false;
constructor(public http: Http, public navCtrl: NavController, public navParams: NavParams, fb: FormBuilder) {
/**Getting events*/
this.http.get(ZEUS_URL + '/evento/fetch', {withCredentials: true}).map(res => res.json()).subscribe(data => {
this.eventos = new Array<Evento>();
data.forEach(element => {
let temp_event = new Evento(element.codEvento, element.codigo, element.descripcion, element.json_plantilla);
this.eventos.push(temp_event);
})
})
/**Getting roles*/
this.http.get(ZEUS_URL + '/rol/fetch', {withCredentials: true}).map(res => res.json()).subscribe(data => {
this.roles = new Array<Rol>();
data.forEach(element => {
let temp_rol = new Rol(element.codRol, element.nombre, element.descripcion, element.eventos);
this.roles.push(temp_rol);
})
})
/**Getting Events from Roles*/
this.http.get(ZEUS_URL + '/rolEventoSuscripcion/fetch', {withCredentials: true}).map(res => res.json()).subscribe( data => {
this.rolEventos = Array<RolEvento>();
data.forEach(element => {
let temp_rolEventos = new RolEvento(element.codRol, element.codEvento);
this.rolEventos.push(temp_rolEventos);
})
for (var i = 0; i <= this.roles.length - 1; i++) {
console.log(this.rolEventos[i])
this.Name.setValue(this.rolEventos[i]);
}
}, err => {
console.log("Error", err)
})
let numRol: number = parseInt(localStorage.getItem('codRol'));
if (numRol === 15) {
this.rolAdmin = true;
}
}
//Versión usando modelo RolEvento
guardar() {
var resultado: RolEventoJSON[] = [];
for (var i = 0; i <= this.roles.length - 1; i++) {
if (typeof this.roles[i].eventos == "undefined") continue;
for (var j = 0; j <= this.roles[i].getEventos().length - 1; j++) {
resultado.push({codRol:this.roles[i].getCodRol(), codEvento:this.roles[i].getEventos()[j].getCodEvento()})
}
}
console.log(resultado)
console.log(JSON.stringify(resultado))
this.http
.post(ZEUS_URL + "/suscripcion", JSON.stringify(resultado),{withCredentials: true})
.subscribe(data => {
console.log("ok")
}, error => {
console.log("error");
});
}
ionViewDidLoad() {
console.log('ionViewDidLoad RolePage');
}
}
<ion-header>
<ion-navbar>
<button ion-button menuToggle>
<ion-icon name="menu"></ion-icon>
</button>
<ion-title>Conf. de roles</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<form>
<ion-list>
<ion-item *ngFor="let rol of roles">
<ion-label>{{rol.nombre}}</ion-label>
<!-- Cada input necesita un modelo (no uno para todos) -->
<ion-select [(ngModel)]="rol.eventos" multiple="true">
<ion-option [value]="evento" *ngFor="let evento of eventos" >{{evento.descripcion}}</ion-option>
</ion-select>
</ion-item>
</ion-list>
<button ion-button icon-right block outline color="botones" (click)="guardar()" type="submit">
Guardar/Submit
<ion-icon name="checkmark-circle-outline"></ion-icon>
</button>
</form>
</ion-content>
The code (doesn't run because its need the data from the backend).
I would like to have checked "ion-option" depending of data from JSON.
Like i am showing a json with only the codes, and not the names, here is the relation:
ROLES TABLE:
'15','ADMIN'
'16','TRAFICO'
'17','RRHH'
'18','ADMINISTRACION'
USERS TABLE:
'43','ALTA TIPO VEHICULO'
'45','BAJA TIPO VEHÍCULO'
Thanks for all!!!