I have a reactive input form with a dynamic amount of inputs that I need to add form controls to.
The parent control Mammals will contain a variable amount of MammalId's, and each MammalId will contain a FormArray of variable length.
I have created typescript code that will generate the form as I described, however, I haven't been able to set my form to my HTML.
And an example of my generated form:
I've tried mapping the form to my html in the following way:
<form [formGroup]="inputForm">
<div *ngFor="let mammal of Mammals; let i = index">
<div *ngFor="let id of mammal.ids; let z = index">
<!-- parent form control -->
<div [formGroupName]="mammals">
<!-- mammals[i].id resolves to 'mammalIdx' -->
<div [formGroupName]="mammals[i].id">
<!-- this should map as the controls Form Array -->
<input [formControlName]="z">
</div>
</div>
</div>
</div>
</form>
But when I try and run this, I get:
Error: Cannot find control with unspecified name attribute
How can I set my html to my form values?
Thank you
The parent control Mammals will contain a variable amount of MammalId's, and each MammalId will contain a FormArray of variable length.
As per my understand the arry you expected may be like this
[
{
"Mammals":[
{
"mammalId":[
{
}
]
}
]
}
]
for that above array the form will be like this
this.inputForm = this.fb.group({
Mammals: this.fb.array([}
mammalId: this.fb.array([{
z: ''
}
])}
])
})
for that above array html should be like this
HTML
<form [formGroup]="inputForm">
<div formArrayName="Mammals">
<div *ngFor="let mammal of inputForm.get('Mammals'); let i = index" [formGroupName]="i">
<div formArrayName="mammalId">
<div *ngFor="let id of mammal.get(mammalId); let z = index" [formGroupName]="z">
<!-- parent form control -->
<!-- mammals[i].id resolves to 'mammalIdx' -->
<!-- this should map as the controls Form Array -->
<input [formControlName]="z">
</div>
</div>
</div>
</div>
</div>
</div>
</form>
It may be helps you
Related
I get string data from my database to my variable, I want to display them as HTML tags by [innerHTML], but it doesn't work.
The variable is displayed on string instead HTML Tags.
I tried to use with DomSanitizer but it don't work:
article:Article[];
(article.articlesTitleHtml:SafeHtml;)
in the function:
this.article.forEach(elementArticle => {
elementArticle.articlesTitleHtml = this.sanitizer.bypassSecurityTrustHtml(elementArticle.articleTitle)
});
in HTML page:
<div *ngFor="let item of articles">
<div id="{{item.articleId}}">
<h2 class="chart" [innerHTML]="item.articlesTitleHtml"></h2>
</div>
my code:
in Type Script:
articles:Article[];
ngOnInit() {
this.apiArticle.getArticleList().subscribe(data=>{
this.articles=data
})
in HTML page:
<div *ngFor="let item of articles">
<div id="{{item.articleId}}">
<h2 class="chart" [innerHTML]="item.articleTitle"></h2>
</div>
</div>
It should work, you can check here...
if you can share the type of data that you're dealing with, it will give more insight into the appropriate DomSanitizer method which should be called
in my example above, i used both bypassSecurityTrustHtml & bypassSecurityTrustUrl for the 2 different types of strings which needed sanitization
On my website if I have more than one element in my array. My template looks like this.
I want to have a button to go to the next element of this array and only display one set of data and use the button to control which element of the array the user sees.
My current code looks like this:
<div class='panel-body' *ngIf ='case'>
<h3> Details </h3>
<div id="left-side" *ngFor="let tag of case?.incidents ">
<p>Date: <span class="name">{{tag.date}}</span> </p>
<p>DCU: <span class="name">{{tag.dcu}}</span></p>
<p>Location:<span class="name"> {{tag.location}}</span> </p>
</div>
I was thinking of using some sort of index or an ng-container or some work around using ngIf or ngFor. I am unsure of how to implement this.
All help would be greatly appreciated!
You're not going to need an ngFor or ngIf in this situation. What you'll want is a variable to keep track of the user's index, and then a function that changes that index.
<h3> Details </h3>
<div id="left-side" >
<p>Date: <span class="name">{{case?.incidents[userIndex].date}}</span> </p>
<p>DCU: <span class="name">{{case?.incidents[userIndex].dcu}}</span></p>
<p>Location:<span class="name"> {{case?.incidents[userIndex].location}}</span> </p>
</div>
<button (click)="changeIndex(-1);">Previous</button>
<button (click)="changeIndex(1);">Next</button>
and in your component.ts you'll have:
userIndex = 0;
changeIndex(number) {
if (this.userIndex > 0 && number < 0 || //index must be greater than 0 at all times
this.userIndex < this.case?.incidents.length && number > 0 ) { //index must be less than length of array
this.userIndex += number;
}
This will be a standard for in-view paging systems for other projects as well.
To achieve this you can use angular's default SlicePipe like this example,
#Component({
selector: 'slice-list-pipe',
template: `<ul>
<li *ngFor="let i of collection | slice:1:3">{{i}}</li>
</ul>`
})
export class SlicePipeListComponent {
collection: string[] = ['a', 'b', 'c', 'd'];
}
You can find more details here
I have a component that show/hide element by clicking a button.
This is my html
<div *ngFor="let history of histories | sortdate: '-dateModified'">
<p><b>{{ history.remarks }}</b> - <i>{{history.dateModified | date:'short'}}</i></p>
<a href="google.com"
[class.datatable-icon-right]="history.$$expanded"
[class.datatable-icon-down]="!history.$$expanded"
title="Expand/Collapse Row"
(click)="toggleExpandRow(history)"></a>
<!-- hide/show this by clicking the button above.-->
<div *ngFor="let step of history.steps; let i = index">
<b>{{i+1}}.</b> {{step}}
<span class="clear"></span>
</div>
<hr />
</div>
and my .ts
toggleExpandRow(row) {
console.log('Toggled Expand Row!', row);
//row
return false;
}
trying to search but, can't find any same sample.
On jquery, I can do this, but on Angular2, I am having hard time to figure this.
There are two options:
1- You can use the hidden directive to show or hide any element
<div [hidden]="!edited" class="alert alert-success box-msg" role="alert">
<strong>List Saved!</strong> Your changes has been saved.
</div>
2- You can use the ngIf control directive to add or remove the element. This is different of the hidden directive because it does not show / hide the element, but it add / remove from the DOM. You can loose unsaved data of the element. It can be the better choice for an edit component that is cancelled.
<div *ngIf="edited" class="alert alert-success box-msg" role="alert">
<strong>List Saved!</strong> Your changes has been saved.
</div>
Use the ngIf in your repeated rows. Create a boolean property called showStep to indicate whether the row should be expanded or not.
<div *ngFor="let step of history.steps; let i = index" ngIf="history.showStep">
<b>{{i+1}}.</b> {{step}}
<span class="clear"></span>
</div>
Then, in your .ts file:
toggleExpandRow(history) {
history.showStep = !history.showStep
//note the same porperty of showStep that is used in your html
}
Extra:
In fact, to save a few lines of codes, you don't even need the toggleExpandRow function at all. You can do it inline in your html:
//other attributes omitted for brevity
<a (click)="history.showStep = !history.showStep">
<div *ngFor="let field of page.fields">
<div #ce class="infills richtextbox textarea {{field.groupid}}" contentEditable="true"
*ngIf="(field.fieldtype=='textarea' && field.isexpandable=='true')"
id="{{field.id}}" name="{{field.id}}"
[ngStyle]="{'position':'absolute','top':field.y+'px','left':field.x+'px',
'font-size':'12px','font-family':'Courier New','height':field.height+'px',
'width':field.width+'px','background':'#EEE'}"
[(ngModel)]="field.value" title="{{field.description}}"
(dblclick)="openFullRTE(field.id)" (focusout)="getHTMLContent()">
</div>
</div>
In ts part,
getHTMLContent() {
console.log(this.ce.nativeElement.innerHTML);
}
When I write anything in first div, respective innerHTML is consoled properly. Then if I write something in second div, console gets overridden by data of first div. Please suggest a way to get HTML content of individual fields and to console them separately.
<div *ngFor="let field of page.fields; let i=index">
<div #ce class="infills ri...
(focusout)="getHTMLContent(i)"
class MyComponent {
#ViewChildren('ce') ces:QueryList<ElementRef>;
constructor(private elRef:ElementRef) {}
getHtmlContent(i) {
console.log(this.ces.toArray()[i].nativeElement.innerHTML);
}
}
The easiest way:
<div *ngFor="let field of page.fields">
<div #ce ... (focusout)="getHTMLContent(ce)">
</div>
</div>
getHTMLContent(element) {
console.log(element.innerHTML);
}
I have a form that submits data into a function called ng-submit="newBirthday() this pushes data - $scope.bdayname, $scope.bdaydate; into an array called bdaes
My issue is that with all of the tutorials I have seen the array has predefined data is there a way that it can be an empty array that gets filled with data when it is submitted?
app.js:
var app = angular.module('birthdayToDo', []);
app.controller('main', function($scope){
// Start as not visible but when button is tapped it will show as true
$scope.visible = false;
// Create the array to hold the list of Birthdays
$scope.bdays = [{}];
// Create the function to push the data into the "bdays" array
$scope.newBirthday = function(){
$scope.bdays.push({name:$scope.bdayname, date:$scope.bdaydate});
$scope.bdayname = '';
$scope.bdaydate = '';
}
});
HTML:
<body ng-app="birthdayToDo" ng-controller="main">
<div id="wrap">
<!-- Begin page content -->
<div class="container">
<div class="page-header">
<h1>Birthday Reminders</h1>
</div>
<ul ng-repeat="bdays in bdays">
<li>{{bdae.name}} | {{bdae.date}}</li>
</ul>
<form ng-show="visible" ng-submit="newBirthday()">
<label>Name:</label>
<input type="text" ng-model="bdayname" placeholder="Name"/>
<label>Date:</label>
<input type="date" ng-model="bdaydate" placeholder="Date"/>
<button class="btn" type="submit">Save</button>
</form>
</div>
<div id="push"></div>
</div>
<div id="footer">
<div class="container">
<a class="btn" ng-click="visible = true"><i class="icon-plus"></i>Add</a>
</div>
</div>
<script type="text/javascript" src="js/cordova-2.5.0.js"></script>
<script type="text/javascript">
app.initialize();
</script>
</body>
Okay, there were a few of small issues.
An empty array must have no items; [{}] is an array with one item: an empty object. Changing to [] gets rid of the extra bullet.
The bigger issue was your ngRepeat. You used ng-repeat="bdays in bdays". What ngRepeat does is take an array and allow you to do a "for each" on the array, assigning each value to that temporary local variable. You named them the same. Instead, ng-repeat="bday in bdays" will add the DOM nodes inside of it for each item in bdays, giving you a local variable called bday to use to reference each item.
Inside the ngRepeat template, you used bdae, which doesn't reference anything.
I don't know what app.initialize() is, so I removed it. It was just erroring out in the console.
Here's a fixed Plunker: http://plnkr.co/edit/OFWY7o?p=preview