Kind of recursive usage of an Component possible? - html

After searching for like two hours for a solution I decided to ask some pros suspecting the solution could be quite simple.
It is an Angular7 project.
I would like to have a "goal" in my goals component with a button "+". When you click that button I want to have annother goal being added to the page. So I want to click a button of the goal component to create a new goal, which is something like recursive to me.
goals.component.html:
<input type="text" value="Ich brauche einen Laptop für maximal 1000 Euro.">
<br/>
<br/>
<app-goal id="{{lastGivenId+1}}"></app-goal>
goals.component.ts:
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'app-goals',
templateUrl: './goals.component.html',
styleUrls: ['./goals.component.scss']
})
export class GoalsComponent implements OnInit {
lastGivenId: number = 0;
constructor() { }
ngOnInit() {
}
}
goal.component.ts and goal.component.html:
//Typescript code
import { Component, OnInit, Input } from '#angular/core';
#Component({
selector: 'app-goal',
templateUrl: './goal.component.html',
styleUrls: ['./goal.component.scss']
})
export class GoalComponent implements OnInit {
#Input() id : number;
constructor() { }
ngOnInit() {
}
onAddLowerGoal(currentGoalID:number){
// var goalElement = document.registerElement('app-goal');
// document.body.appendChild(new goalElement());
let newGoal = document.createElement("app-goal");
newGoal.setAttribute("id", "999");
let currentGoal = document.getElementById(currentGoalID.toString());
document.body.insertBefore(newGoal, currentGoal);
}
}
<html>
<div id="{{id}}" class="goal">goal{{id}}</div>
<button id="AddLowerGoal1" (click)="onAddLowerGoal(999)">+</button>
</html>
This way, it creates an app-goal element, but the div and button elements within the app-goal element is missing.
How can this problem be solved? Any help is welcome. Thanks in advance.

First glance: delete the html tags from your goal.component.html file.
Next: you can recursively add app-goal using angular. Inserting app-goal element the javascript way only adds the <app-goal></app-goal> object. It doesn't create an angular component. It doesn't bind your data.
Also if you're using Angular's #Input, you need to assign a component input with square braces. Do not use tags.
goals.component.html:
<input type="text" value="Ich brauche einen Laptop für maximal 1000 Euro.">
<br/>
<br/>
<app-goal [id]="lastGivenId+1"></app-goal>
goal.component.html:
<div id="{{id}}" class="goal">goal{{id}}</div>
<button id="AddLowerGoal1" (click)="onAddLowerGoal(999)">+</button>
<div *ngFor="let subGoal of subGoals">
<app-goal [id]="subGoal.id"></app-goal>
</div>
goal.component.ts:
import { Component, OnInit, Input } from '#angular/core';
#Component({
selector: 'app-goal',
templateUrl: './goal.component.html',
styleUrls: ['./goal.component.scss']
})
export class GoalComponent implements OnInit {
#Input() id : number;
subGoals: Array<any> = [];
constructor() { }
ngOnInit() { }
onAddLowerGoal(currentGoalID: number){
this.subGoals.push({id: currentGoalID});
}
}
You can also use a service to store your goals and subgoals to access them later.

I think what you're looking for is a Reactive Form with FormArray with dynamically added form controls.
Take a look at this for eg:
import { Component } from '#angular/core';
import { FormControl, FormGroup, FormArray, FormBuilder } from '#angular/forms';
#Component({...})
export class GoalsComponent {
goalsForm: FormGroup;
constructor(private fb: FormBuilder) {}
ngOnInit() {
this.goalsForm = this.fb.group({
goals: this.fb.array([])
});
}
onFormSubmit() {
console.log('Form Value: ', this.goalsForm.value);
}
get goals() {
return (<FormArray>this.goalsForm.get('goals')).controls;
}
addGoal() {
(<FormArray>this.goalsForm.get('goals')).push(this.fb.control(null));
}
}
And here's the template for this:
<h2>Goals:</h2>
<form [formGroup]="goalsForm" (submit)="onFormSubmit()">
<button type="button" (click)="addGoal()">Add Goal</button>
<hr>
<div *ngFor="let goal of goals; let i = index;" formArrayName="goals">
<div>
<label for="goal">Goal {{ i + 1 }}: </label>
<input type="text" id="goal" [formControlName]="i">
</div>
<br>
</div>
<hr>
<button>Submit Form</button>
</form>
Here's a Sample StackBlitz for your ref.

Related

Angular: sanitizer.bypassSecurityTrustHtml does not render attribute (click)

I try to render a button and it works fine, but when I click the button it doesn't execute alertWindow function, help!:
app.component.ts:
import {
Component,
ElementRef,
OnInit,
ViewEncapsulation } from '#angular/core';
import { DomSanitizer, SafeHtml } from "#angular/platform-browser";
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
encapsulation: ViewEncapsulation.ShadowDom,
})
export class AppComponent implements OnInit {
public content: SafeHtml;
constructor(private sanitizer: DomSanitizer) {}
async ngOnInit() { this.renderButton(); }
alertWindow() { alert("don't work"); }
renderButton() {
this.content =
this.sanitizer.bypassSecurityTrustHtml(`
<button (click)='connectWallet()' class="button">
Connect your wallet
</button>`);
}
app.component.ts;
<div [innerHTML]="content"></div>
Solution
Based on what I understand you wanted to display HTML dynamically at runtime? then solution is to use
ComponentFactoryResolver
and ViewContainerRef
It will be better if you can provide more details, what you are trying to achieve, so that people can guide you
Why it didn't work?
It doesn't work because it is outside of angular, when you use innerHTML then whatever you passed to it is pure vanilla HTML and JavaScript
Try this example
(window as any).alertWindow = function () {
alert("don't works");
};
#Component({...})
export class AppComponent {
...
renderButton() {
this.content = this.sanitizer.bypassSecurityTrustHtml(`
<button onclick='alertWindow()' class="button">Connect your wallet</button>
`);
}
}
It works right?
As you can see I have moved alrertWindow function outside of component's class and added to window variable and also changed (click) to onclick

Angular textarea input not showing value/contents, despite showing up in html

I insert a textarea component into my template like so:
<div class="card-body" *ngIf="isEditing">
<app-text-area input-id="body" input-value="This is my default input value"></app-text-area>
</div>
The template of app-text-area is like so:
<textarea
placeholder="This is my placeholder"
[name]="inputID"
(input)="onInputChanged($event)"
ngModel>
{{ inputValue }}
</textarea>
The subsequent rendered HTML is like so:
<textarea _ngcontent-owj-c62="" placeholder="This is my placeholder" ngmodel="" ng-reflect-model="" ng-reflect-name="body" class="ng-pristine ng-valid ng-touched">
This is my default input value
</textarea>
However on the actual page, the inputValue text doesn't show up anywhere, the textarea acts as though it is empty, even showing the placeholder text. I can see the value in the html, though when I start typing in the box it replaces it as if it weren't there. The console shows no errors.
If I remove ngModel from the textarea, it fixes it
My app-text-area component ts is:
import { Component, EventEmitter, Input, OnInit, Output } from '#angular/core';
import { ControlContainer, NgForm } from '#angular/forms';
#Component({
selector: 'app-text-area',
templateUrl: './text-area.component.html',
viewProviders: [ { provide: ControlContainer, useExisting: NgForm } ],
styleUrls: ['./text-area.component.scss']
})
export class TextAreaComponent implements OnInit {
#Input("input-id") public inputID: string = "text";
#Input("input-value") public inputValue: string;
constructor() { }
ngOnInit(): void {
}
public onInputChanged(event: Event):void {
let newValue = (event.target as HTMLTextAreaElement).value;
this.inputValue = newValue;
}
}
Hard to help without seeing the component.ts file
But a solution would be something in the lines of the following:
HTML template:
<textarea
[name]="inputID"
(input)="onInputChanged($event)"
[value]="inputValue">
</textarea>
<p>{{inputValue}}</p>
And the component.ts:
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'app-text-area',
templateUrl: './text-area.component.html',
styleUrls: ['./text-area.component.css']
})
export class TextAreaComponent implements OnInit {
inputID:number=1;
inputValue:string="This is my placeholder";
constructor() { }
ngOnInit(): void {
}
onInputChanged(event:any){
this.inputValue=event.target.value;
}
}
This would set the initial value as "This is my placeholder" and would update the value on each change in the input displayed inside the p tag
I managed to fix this by setting [ngModel]="inputValue" instead of the defaultValue, value, or placing inputValue inside the textarea itself.

How to get the selected value from one component to other using event emitter in angular 8

I have 2 components , one login and other home. When I change drop down into login component ,selected value need to display in home component. I am already emitting the onchange event from login component to home component and displaying the value but still I am not getting the value into home component.Here is the code below
login.component.html
<select #mySelect (change)="onOptionsSelected(mySelect.value)">
<option value="one">one</option>
<option value="two">two</option>
</select>
login.component.ts
import { Component, OnInit,Input,Output, EventEmitter } from '#angular/core';
import { Router } from '#angular/router';
#Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
#Output() buttonClicked = new EventEmitter();
constructor(private router: Router) { }
#Input() item: string;
ngOnInit() {
}
onOptionsSelected(value:string){
console.log("the selected value is " + value);
this.buttonClicked.emit(value);
this.router.navigateByUrl('/home');
}
}
home.component.html
<p>home works!</p>
<app-login (buttonClicked)='showNextComponent($event)'></app-login>
<p>Hello {{ name }} </p>
home.component.ts
import { Component, OnInit,ElementRef,ViewChild } from '#angular/core';
import { CommonserviceService } from './../utilities/services/commonservice.service';
import { LoginComponent } from '../login/login.component';
#Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
getListData: any;
constructor(private commonserviceService: CommonserviceService) { }
name:string
ngOnInit() {
}
showNextComponent(value:string) {
this.name = value;
console.log(this.name);
}
}
I pasted your code here in stackblitz: https://stackblitz.com/edit/angular-cfkqns
You are correctly emitted values up to the parent component and binding the value to be displayed in the parent component.
It is working how you expect it to :-)
UPDATE:
I have answered the same question for some one else here:
https://stackoverflow.com/a/64082745/450388
however I have updated your stackblitz to reflect how to achieve the same.
https://stackblitz.com/edit/angular-cfkqns

How to block duplicate values while inserting value into an array?

How to prevent duplicate values during insert record into an array using angular6+
PARENTCOMPONENT.HTML:
<div class="form-group" style="margin-left:30px;margin-top:30px;">
<input type="text" class="form-control" placeholder="Posts" name="post" [(ngModel)]="post" #clearText>
</div>
<button type="submit" class="btn btn-sm btn-primary" (click)="AddServer(post)"
style="margin-left:30px;margin-top:10px;" (blur) = "clearText.value = ''">Click</button>
<app-child [childPost]="parentPosts"></app-child>
PARENTCOMPONENT.TS:
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'app-parent',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.css']
})
export class ParentComponent implements OnInit {
post = '';
parentPosts: any[] = [];
constructor() { }
ngOnInit() {
}
AddServer(post)
{
this.parentPosts.push(post);
console.log(post);
}
}
CHILDCOMPONENT.HTML:
<div style="margin-left: 30px; margin-top:10px;" *ngFor="let p of childPost">
<p>{{p}}</p>
</div>
CHILDCOMPONENT.TS:
import { Component, OnInit, Input } from '#angular/core';
#Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
#Input() childPost: any[] = [];
constructor() { }
ngOnInit() {
}
}
Hi guys the above code was insert data from parent component to child component using textbox values and button in that PARENCOMPONENT.TS code what i need is during the time of pushing value into an array the values must be unique if i post repeated value it throws an alert or error message the value was already inserted like that so please kindly help me to resolve this....
You could use Set data structure that will omit duplicate Insertions which is better then having an extra loop to verify if it's already in the array and then omit it.
parentPosts: Set = new Set();
// then use it like
this.parentPosts.add(post); // if post already exists it'll just not add it
Test if it contains it first
if (!this.parentPosts.includes(post)) {
this.parentPosts.push(post);
}

How to get check particular checkboxes by default based on some values in angular 7

I have a checkboxes and selectbox whose values are coming from loop,but here I need to get some checkboxes checked by default based on an array of object.Here checkbox and selectbox value is coming from usersg and usersr variable.But the checked and selected by default should be from variable usersg_checked and usersr_selected inside ngOnInit(). Here is the code below
home.component.html
<p *ngFor="let group of usersg"><input type="checkbox" checked="checked.id" value="{{group.id}}" />{{group.name}}</p>
<p><select><option *ngFor="let role of usersr" value="{{role.id}}">{{role.name}}</option></select></p>
home.component.html
import { Component, OnInit } from '#angular/core';
import { CommonserviceService } from './../utilities/services/commonservice.service';
#Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
submitted = false;
usersg_checked:any;
usersr_selected:any;
constructor(private formBuilder: FormBuilder) {
}
public usersg = [{"id":1,"name":"test1"},{"id":2,"name":"test2"},{"id":3,"name":"test3"},{"id":4,"name":"test4"}];
public usersr = [{"id":1,"name":"test1"},{"id":2,"name":"test2"}];
ngOnInit() {
this.usersg_checked = [{"id":1,"name":"test1"},{"id":2,"name":"test2"}];
this.usersr_selected = [{"id":1,"name":"test1"}];
}
}
Add isChecked() method in component to check if a checkbox must be selected.
Component:
isChecked(id) {
return this.usersg_checked.some(item => item.id === id);
}
Template:
<p *ngFor="let group of usersg">
<input type="checkbox" [checked]="isChecked(group.id)" value="{{group.id}}" />{{group.name}}
</p>
For <select> elements better to use [(ngModel)].
Template:
<p><select [(ngModel)]="usersr_selected.id">
<option *ngFor="let role of usersr" value="{{role.id}}">{{role.name}}</option>
</select></p>
Component:
And change usersr_selected to an object.
ngOnInit() {
this.usersr_selected = {"id":1,"name":"test1"};
}
If usersr_selected is an array, use the first element of the array as NgModel.
ngOnInit() {
this.usersr_selected = this.usersr_selected[0];
}