2017-04-10 98 views
1

需要將對話框滾動到頂部,以便表單提交後警報進入視圖。 試過這個,但似乎沒有在對話框上工作。Angular2 - 如何將對話框滾動到頂部

window.scrollTo(0,0); 
+0

所以,你想,如果你提交一個表單,滾動到頂部,並且應該有一個對話呢?或者是對話框需要滾動的一些可滾動內容? – Randy

+0

打開對話框 - >對話框中的長表單 - >提交 - >滾動到對話框頂部,以顯示錯誤提示。 –

回答

1

document.getElementById('formsubmit').onclick=function(){ 
 
    document.getElementById('form').scrollTop = 0; 
 
    return false; 
 
}
input { 
 
    display:block; 
 
} 
 

 
.form { 
 
    height:100px; 
 
    overflow-y:auto; 
 
}
<div> 
 
    <h1>form</h1> 
 
    <div class="form" id="form"> 
 
    <input type="text"> 
 
    <input type="text"> 
 
    <input type="text"> 
 
    <input type="text"> 
 
    <input type="text"> 
 
    <input type="text"> 
 
    <input type="text"> 
 
    
 
    <input type="submit" id="formsubmit"> 
 
    </div> 
 
</div>

+0

試過了,但似乎沒有工作。它看起來像對話不受scrollTop影響。儘管我已經通過檢查「document.getElementById('form')。scrollTop = 0;」之前和之後的值來滾動到底部,但該值仍然爲0。 –

+1

@KarlisFilipsons你確定這個對話框是可滾動的嗎?它可以是對話框中的「div」。 – Randy

+0

啊,你說得對。我沒有在正確的元素上使用它。現在就像魅力一樣。謝謝! –

1

儘管這個問題已經被標記爲答案,這不是滾動到頂部的角度-Y方式。這樣做的更好的方式是通過做:

@ViewChild('scrollContainer') private myScrollContainer: ElementRef; 
 
    
 
constructor(private _renderer: Renderer2) {} 
 
onFormSubmit() { 
 
    this._renderer.setProperty(this.scrollContainer.nativeElement, 'scrollTop', this.scrollContainer.nativeElement.scrollHeight); 
 
}
input { 
 
    display:block; 
 
} 
 

 
.form { 
 
    height:100px; 
 
    overflow:auto; 
 
}
<div> 
 
    <h1>form</h1> 
 
    <div #scrollContainer class="form"> 
 
     <input type="text"> 
 
     <input type="text"> 
 
     <input type="text"> 
 
     <input type="text"> 
 
     <input type="text"> 
 
     <input type="text"> 
 
     <input type="text"> 
 
     <input type="submit" (click)="onFormSubmit()"> 
 
    </div> 
 
</div>

一個好的經驗法則是,如果你看到```document``那麼你沒有做什麼角度來說,但香草的方式。

一個很大的錯誤,人們普遍提出的是,他們使用的ElementRef到setValues方法,屬性,CSS。根據角度文檔,ElementRef應該被用作最後的手段。你可以閱讀更多有關在這裏:https://angular.io/api/core/ElementRef