각도 2 요소 표시 및 숨기기
Angular 2의 부울 변수에 따라 요소를 숨기고 표시하는 데 문제가 있습니다.
이것은 div가 표시하고 숨기는 코드입니다.
<div *ngIf="edited==true" class="alert alert-success alert-dismissible fade in" role="alert">
<strong>List Saved!</strong> Your changes has been saved.
</div>
변수는 "편집"되었으며 내 구성 요소에 저장됩니다.
export class AppComponent implements OnInit{
(...)
public edited = false;
(...)
saveTodos(): void {
//show box msg
this.edited = true;
//wait 3 Seconds and hide
setTimeout(function() {
this.edited = false;
console.log(this.edited);
}, 3000);
}
}
saveTodos 함수가 시작되면 요소가 숨겨 지지만 요소가 표시되지만 3 초 후에 변수가 다시 false로 바뀌더라도 요소가 숨겨지지 않습니다. 왜?
* ngIf 지시어를 사용해야합니다
<div *ngIf="edited" class="alert alert-success box-msg" role="alert">
<strong>List Saved!</strong> Your changes has been saved.
</div>
export class AppComponent implements OnInit{
(...)
public edited = false;
(...)
saveTodos(): void {
//show box msg
this.edited = true;
//wait 3 Seconds and hide
setTimeout(function() {
this.edited = false;
console.log(this.edited);
}.bind(this), 3000);
}
}
업데이트 : Timeout 콜백 내에있을 때 외부 범위에 대한 참조가 누락되었습니다.
위의 추가와 같이 .bind (this)를 추가하십시오.
Q : 편집은 전역 변수입니다. * ngFor-loop 내에서 당신의 접근 방식은 무엇입니까? – Blauhirn
A : 반복하는 객체에 속성으로 편집을 추가하고 싶습니다.
<div *ngFor="let obj of listOfObjects" *ngIf="obj.edited" class="alert alert-success box-msg" role="alert">
<strong>List Saved!</strong> Your changes has been saved.
</div>
export class AppComponent implements OnInit{
public listOfObjects = [
{
name : 'obj - 1',
edit : false
},
{
name : 'obj - 2',
edit : false
},
{
name : 'obj - 2',
edit : false
}
];
saveTodos(): void {
//show box msg
this.edited = true;
//wait 3 Seconds and hide
setTimeout(function() {
this.edited = false;
console.log(this.edited);
}.bind(this), 3000);
}
}
달성하고자하는 것에 따라 두 가지 옵션이 있습니다.
You can use the hidden directive to show or hide an element
<div [hidden]="!edited" class="alert alert-success box-msg" role="alert"> <strong>List Saved!</strong> Your changes has been saved. </div>
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>
For you problem of change after 3 seconds, it can be due to incompatibility with setTimeout. Did you include angular2-polyfills.js library in your page ?
When you don't care about removing the Html Dom-Element, use *ngIf.
Otherwise, use this:
<div [style.visibility]="(numberOfUnreadAlerts == 0) ? 'hidden' : 'visible' ">
COUNTER: {{numberOfUnreadAlerts}}
</div>
For child component to show I was using *ngif="selectedState == 1"
Instead of that I used [hidden]="selectedState!=1"
It worked for me.. loading the child component properly and after hide and un-hide child component was not undefined after using this.
This is a good use case for a directive. Something like this is surprisingly useful.
@Directive({selector: '[removeAfter]'}) export class RemoveAfter {
constructor(readonly element: ElementRef<HTMLElement>) { }
/**
* Removes the attributed element after the specified number of milliseconds.
* Defaults to (1000)
*/
@Input() removeAfter = 1000;
ngOnInit() {
setTimeout(() => {
this.element.nativeElement.remove();
}, this.removeAfter);
}
}
We can do it by using the below code snipet..
Angular Code:
export class AppComponent {
toggoleShowHide:string ="visible";
}
Html Template:
Enter text to hide or show item in bellow:
<input type="text" [(ngModel)]="toggoleShowHide">
<br>
Toggle Show/hide:
<div [style.visibility]="toggoleShowHide">
Final Release Angular 2!
</div>
Depending on your needs, *ngIf
or [ngClass]="{hide_element: item.hidden}"
where CSS class hide_element
is { display: none; }
*ngIf
can cause issues if you're changing state variables *ngIf
is removing, in those cases using CSS display: none;
is required.
@inoabrian solution above worked for me. I ran into a situation where I would refresh my page and my hidden element would reappear on my page. Here's what I did to resolve it.
export class FooterComponent implements OnInit {
public showJoinTodayBtn: boolean = null;
ngOnInit() {
if (condition is true) {
this.showJoinTodayBtn = true;
} else {
this.showJoinTodayBtn = false;
}
}
Just add bind(this) in your setTimeout function it will start working
setTimeout(function() {
this.edited = false;
console.log(this.edited);
}.bind(this), 3000);
and in HTML change
<div *ngIf="edited==true" class="alert alert-success alert-dismissible fade in" role="alert">
<strong>List Saved!</strong> Your changes has been saved.
</div>
To
<div *ngIf="edited" class="alert alert-success alert-dismissible fade in" role="alert">
<strong>List Saved!</strong> Your changes has been saved.
</div>
참고URL : https://stackoverflow.com/questions/35163009/angular-2-show-and-hide-an-element
'programing tip' 카테고리의 다른 글
경로에 대한 액세스가 거부되었습니다 (0) | 2020.06.07 |
---|---|
항목이 변경 될 때 ObservableCollection이 알리지 않음 (INotifyPropertyChanged를 사용하더라도) (0) | 2020.06.07 |
Go를 사용하여 JSON을 예쁘게 인쇄하려면 어떻게해야합니까? (0) | 2020.06.06 |
모듈을 만들 수 없습니다 : 관련 gradle 구성을 찾을 수 없습니다. (0) | 2020.06.06 |
org.hibernate.LazyInitializationException 수정하는 방법-프록시를 초기화 할 수 없습니다-세션 없음 (0) | 2020.06.06 |